Download as pdf or txt
Download as pdf or txt
You are on page 1of 48

Object-Orientation - A Conceptual Look

Objectives
Functional approach Changing requirements An alternative

The Way We Think


Traditional software development focuses on functions and how they manipulate data A natural way to deal with complexity Big functions that decompose into smaller functions The problem is Requirements Change Functional decomposition might not handle change well A change to one function or piece of data Can cause unwanted side effects High level level functions depend upon the details of low level functions The ripple effect More likely to have problems in your software As people we think about things and what they do A more abstract way of thinking Handles change well

Attending Class - An Example


I have a problem to solve I am teaching you this class After you are finished with my class, you have another to attend You do not know where that class is located I must make sure you know how to get to your next class Its another Keane class and we want you there!

How would I solve this problem?

How well will the solution adapt to change?

The Functional Approach


A functional solution to the problem Get list of people in class For each person on the list Determine next class they need to attend Determine location of the class Formulate directions from my class to the next class Tell the person the instructions Implementing this approach would require A procedure to get the list of people A procedure to get each person's schedule A program to give directions A controlling program to execute these functions for each person

An alternative solution

An Alternative

Post directions to classroom locations on the wall Tell people in class where directions are and to go to their next class Implementing this approach would require People that Know how to read directions With directions, can get to next class A control program to Post the instructions and tell people that class is over A shift of responsibility With the functional approach, The control program is responsible for everything With this alternative, students are responsible for themselves
Which solution feels more natural?

Anew requirement forin problem A Change the Requirements


Keane employees can also audit classes Among other duties, they will collect evaluations for the instructor before going to the next class Impact on functional solution? Change control program Must now determine if the person is a Keane employee or student If the type is employee, tell it to collect evaluations Could take considerable work!

Impact on alternative solution? Write additional routine for people who are employees Control program is unchanged People, go to your next class!

How Does It Work?


People are responsible for themselves
They do their own work They know what type of person they are

Control program
Communicates with all people as if they are the same Does not care how people get from one class to another Does not care if people need to take special

Object-Orientation
In the alternative solution Communication occurred at a conceptual level Tell people what to do, but not how to do it Know what is happening, but not how it is done People performed at a lower level Implementation level They have specific steps and logic to get from one class to another This is the structure provided by Object-Orientation Objects are responsible for themselves Objects tell each other to do things at a conceptual level

Objectives
Objects
State, behavior, identity Instantiation

Classes
Visibility

The three pillars


Encapsulation Inheritance Polymorphism

Objects
Objects are abstractions we use to model things in the real world Student, location, account, product, customer, accident A definition for objects depends upon your perspective Conceptual Objects are things with responsibilities Specification Objects are sets of behavior and attributes May be called by other objects or itself Implementation Packets of code and data

Attributes
Attributes Are variables belonging to an object Student has a name, address and GPA John Park, 2309 Riverside Dr, 3.5 Have a type Name is a string, address is a string, GPA is a float Define the state of an object An object might behave differently depending upon its state One object may have another object as an attribute A student is registered for and keeps track of multiple classes

Behavior
Operations specify what an object can do Call operations to activate object responsibilities Student object, goToNextClass( ) Parameters may be passed into operations Defined by the operation signature Operations may return information Calling an operation could change the state of the object Cause a change to its attributes The list of operations an object supports is its interface Objects collaborate with other objects by sending messages Called object receives the message Invokes the appropriate operation
Operations are identified with ( ) at the end of the operation name

Identity
Each object has a unique existence in space and time Makes it different from every other object Known as the object's identity In implementation terms When an object is created, it resides at a specific place in memory This memory location is not shared with other objects Specific objects are tracked with references Identity is independent of state Changing the value of one object's attributes will not affect another object's attributes Even if two objects have identical values for their attributes Unless we specify behavior to do so

Classes
A class is a template for a set of objects It defines The object's type The attribute types an object will have The values can be different for each object The operations the object will support Think of classes to objects as A blueprint to a house A cookie cutter to the actual cookies A database table to rows in the table Classification is a powerful concept Allows us to talk about features and behavior that every object will have Without having to specify each object

Instantiation
Objects are created from class specifications This process is know as instantiation The object is an instance of the class Classes have special operations called constructors Called to create a new instance Allocates memory for the object (gives it identity) Initializes the attributes May be set to default values or passed as attributes Returns a reference to the new object Eliminates errors associated with uninitialized variables

Objects in Action
A sneak peak at UML notation! Heres some Java. Notice how concept maps to code. Class

Student
name : String address : String gpa : float Attributes

class Student { String name; String address; float gpa; public void goToClass( ) { // code here } public Student(String argName) { name = argName; } }

Constructor

goToClass( ) Student(name: String)

Operations

<<instanceof>>

<<instanceof>>

<<instanceof>>

s1:Student name = Chris


ts

s2:Student name = Mike

s3:Student name = Chris Student s1 = new Student(Chris); Student s2 = new Student(Mike); Student s3 = new Student(Chris);

Ob jec

Objects in Action
A sneak peak at UML notation! Same thing in C#. Notice how concept maps to code. Class

Student
name : String address : String gpa : float Attributes

class Student { string name; string address; float gpa; public void goToClass( ) { // code here } public Student(string argName) { name = argName; } }

Constructor

goToClass( ) Student(name: String)

Operations

<<instanceof>>

<<instanceof>>

<<instanceof>>

s1:Student name = Chris


ts

s2:Student name = Mike

s3:Student name = Chris Student s1 = new Student(Chris); Student s2 = new Student(Mike); Student s3 = new Student(Chris);

Ob jec

Classes

Classes
Class Declaration

public The public modifier declares that the class can be used by any class regardless of its package.

Classes
Class Declaration abstract
Declares that the class cannot be instantiated Declares that the class cannot be subclassed.

final class NameOfClass The class keyword indicates to the compiler that this is a class declaration the name of the class is NameOfClass. extends Super
The extends clause identifies Super as the superclass of the class Declares that your class implements one or more interfaces

implements Interfaces

Classes:Class body
The class body contains all of the code that provides for the life cycle of the objects created from it constructors variables methods Variables and methods collectively are called members. Constructors are not methods. Nor are they members.

Classes: Constructors
All Java classes have constructors that are used to initialize a new object of that type A constructor has the same name as the class A class can have any number of constructors A constructor uses its arguments to initialize the new object's state The default constructor is automatically provided by the runtime system for any class that contains no constructors Superclass constructor must be the first statement in the subclass's constructor

Classes: Member variables


Declaration should be within the class body but outside of any methods or constructors
private Vector items;

Classes: Implementing methods


A method has two major parts: method declaration and method body

Classes: Implementing methods


Method declaration

Classes: Implementing methods


Passing information to methods Declare the type and name for each argument in the method signature

double computePayment(double loanAmt, double rate,


double futureValue, int numPeriods) { double I, partial1, denominator, answer; I = rate / 100.0; partial1 = Math.pow((1 + I), (0.0 - numPeriods)); denominator = (1 - partial1) / I; answer = ((-1 * loanAmt) / denominator) - ((futureValue * partial1) / denominator); return answer; }

Classes:Implementing methods
Passing information to methods Argument Types
An argument can be any valid Java data type into a method A method argument can have the same name as one of the class's member variables

Argument Names

Pass by Value Arguments are passed by value.


primitive type -> pass-by-value means that the method cannot change its value It cannot change the object reference It can modify the accessible variables within the object

reference type -> pass-by-value means that


Classes
Implementing methods Method body
class Stack { static final int STACK_EMPTY = -1; Object[] stackelements; int topelement = STACK_EMPTY; . . . boolean isEmpty() { if (topelement == STACK_EMPTY) return true; else return false; } Object pop() { if (topelement == STACK_EMPTY) return null; else { return stackelements[topelement--]; } } }

Classes

Method body
It may contain declarations for variables that are local to that method this can be used in the method body to refer to members in the current object

super to refer to members in the superclass

Classes
Access Control Classes can protect their member variables and methods from access by other objects Access specifiers to protect both a class's variables and its methods

Specifier Private Protect ed Public


None (Package)

Class

Sub Class

Packa ge

World

Classes:Implementing methods
Instance and Class members
Instance variable Every time you create an instance of a class the runtime system creates one copy of each class's instance variables for the instance Class variables The runtime system allocates class variables once per class regardless of the number of instances created of that class All instances share the same copy of the class's class variables You can access class variables through an instance or through the class itself

Constructors & Consistent State


Consistency -- Constancy /Reliability/Stability Consider the class Kid here public class Kid { public int age; public String name; public void printKid() { System.out.println("Name : " + this.name + ", Age : " + this.age); } } And we have the driver here to drive this code as Kid k = new Kid(); k.printKid(); //Kid created but not consistent k.age = 13; k.name = "Craig"; //Now consistent k.printKid(); k.age = -1; //Inconsistent Data k.printKid();

Constructors & Consistent State


1. Proper construction validate initializing data 2. Hide data public class Kid { private int age; private String name; public Kid(String name, int age) { this.name = name; this.age = (age > 1 && age < 13)? age : 2; } public void printKid() { System.out.println("Name : " + this.name + ", Age : + this.age); } }

Constructors & Consistent State


public class Driver { public static void main(String[] args) { Kid k = new Kid("Craig", 10); k.printKid(); Kid k1 = new Kid("pqr", -1); k1.printKid(); } }

The output now is :


Name : Craig, Age : 10 Name : pqr, Age : 2

Constructors & Consistent State


It is better to provide a default (No argument) constructor and chain the constructor with default values

public class Kid { //private members

public Kid(String name, int age) { this.name = name; this.age = (age > 1 && age < 13)? age : 2; } public Kid() { this("No Name", 2); //Chain the constructor } //printKid method }

Constructors & Consistent State


This would allow us to use the Kid class as-- public class Driver { public static void main(String[] args) { Kid k = new Kid("Craig", 10); k.printKid(); Kid k1 = new Kid(); k1.printKid(); } }
The output now is: Name : Craig, Age : 10 Name : No Name, Age : 2 Now thats even better

Constructors & Consistent State


We have made all the data private. How do we make it accessible to others ? public class Kid { private int age; //note naming convention private String name; //Constructors here public int getAge() //note naming convention { return age; } public void setAge(int age) //note naming convention { this.age = (age > 1 && age < 13)? age : 2; } public String getName() { return name; } public void setName(String name) { this.name = (name.length()== 0)? "No name" : name; }}

Constructors & Consistent State


Using these in the Driver would mean -- public class Driver { public static void main(String[] args) { Kid k = new Kid(); k.setName("Craig"); k.setAge(10); System.out.println(" Name = " + k.getName()); System.out.println(" Age = " + k.getAge()); } } With the output being Name = Craig Age = 10

Constructors & Consistent State Busting Jargons


Getter methods are also known as accessors as they allow us to access data Setter methods are also known as mutators as they allow us to set or mutate data A class with no mutator methods having all private data members with accessors only is known as an immutable class Classes which have only private data members and the relevant accessor and mutator methods are known as POJO (Plain Old Java Object) classes

1. Consider the following class: public class IdentifyMyParts { public static int x = 7; public int y = 3; } a. How many class variables does the IdentifyMyParts class contain? What are their names? b. How many instance variables does the IdentifyMyParts class contain? What are their names?

Quiz:Classes

c. What is the output from the following code:

Quiz:Classes
IdentifyMyParts a = new IdentifyMyParts(); IdentifyMyParts b = new IdentifyMyParts(); a.y = 5; b.y = 6; a.x = 1; b.x = 2; System.out.println("a.y = " + a.y); System.out.println("b.y = " + b.y); System.out.println("a.x = " + a.x); System.out.println("b.x = " + b.x);

Exercises:Classes
1. Write a class whose instances represent a playing card from a deck of cards. 2. Write a class whose instances represent a deck of cards. 3. Write a small program to test your deck and card classes. The program can be as simple as creating a deck of cards and displaying its cards.

POS Class Exercise


Create a Point Of Sale (POS) application as per the following specification package com.caritor.pos Class Item : Immutable, only all param constructor Attributes : int sku, double price, String name Class Catalogue : Singleton Attributes : Contains a HashMap, Add 10 Items in the constructor using sku as the key Method findItem(): Takes sku and return Item, null if sku is not found

POS Class Exercise


Class SaleItem : Immutable, only all param constructor- not public Attributes : Item for sale, int quantity Methods : getLinePrice() : return Item.price * quantity printLine() : Prints sku, name, price, qty and Lineprice Class Sale : default constructor Attributes : Contains an arrayList (private) Methods : addItem(sku, qty):Find the item from the catalog item above and add it to the arraylist getTotalprice(): return the sum of all the Lineprice of the items in the arraylist printReceipt(): print a header then call printLine of all the items, print total price Construct a SaleItem object using the passed in qty and

POS Class Exercise


package com.somestore.terminal
Class Driver:

Method main():

Create a new sale Add few items with sku and qty Print the receipt

Encapsulation
Objects should be self contained
When you tell a dog to fetch, you do not worry about the details of how he or she does it Objects should encapsulate their implementation details away from clients
Keep data hidden
Attributes are not made public Prevents data corruption Access is controlled by getter and setter methods Business rules are kept in once place!

Hide away implementation details


Operations are public, but their implementation is hidden Other objects that interact with them (use their operations) should not be aware of how the operations are

Quiz - Encapsulation
If you know a subclass will need to access your classes attributes, is it OK to declare them as protected?

You might also like