lect - oops

48
Obj ect- Orientati on - A Conceptual Look

Upload: vaibhav-chordia

Post on 05-Apr-2018

225 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 1/48

Object-Orientation - AConceptual Look

Page 2: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 2/48

Objectives – Functional approach

 – Changing requirements

 – An alternative

Page 3: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 3/48

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

Page 4: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 4/48

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• It’s another Keane class and we want you there!

How well will thesolution adapt to

change?

How would I solvethis problem?

Page 5: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 5/48

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 functionsfor each person

Page 6: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 6/48

An Alternative• An alternative solution

 – 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 solutionfeels more natural?

Page 7: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 7/48

A Change in Requirements• A new requirement for the problem

 – 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!

Page 8: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 8/48

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

Page 9: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 9/48

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

Page 10: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 10/48

Objectives – Objects

• State, behavior, identity

• Instantiation – Classes

• Visibility

 – The three pillars• Encapsulation

• Inheritance

• Polymorphism

Page 11: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 11/48

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

Page 12: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 12/48

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

Page 13: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 13/48

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 theend of the operationname

Page 14: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 14/48

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 affectanother object's attributes

• Even if two objects have identical values for their attributes

• Unless we specify behavior to do so

Page 15: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 15/48

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 behaviorthat every object will have

• Without having to specify each object

Page 16: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 16/48

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

Page 17: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 17/48

Objects in ActionA sneak peak

at UML notation!

Studentname : Stringaddress : Stringgpa : float

goToClass( )Student(name: String)

Class

Attributes

Operations

s1:Studentname = “Chris”

Constructor

s2:Studentname = “Mike”

s3:Studentname = “Chris”

   O    b    j   e  c

   t  s

<<instanceof>> <<instanceof>> <<instanceof>>

class Student {

String name;String address;

float gpa;

public void goToClass( ) {

// code here

}

public Student(String argName) {

name = argName;

}

}

Student s1 = new Student(“Chris”);

Student s2 = new Student(“Mike”);

Student s3 = new Student(“Chris”);

Here’s someJava. Notice how concept

maps to code.

Page 18: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 18/48

Objects in ActionA sneak peak

at UML notation!

Studentname : Stringaddress : Stringgpa : float

goToClass( )Student(name: String)

Class

Attributes

Operations

s1:Studentname = “Chris”

Constructor

s2:Studentname = “Mike”

s3:Studentname = “Chris”

   O    b    j   e  c

   t  s

<<instanceof>> <<instanceof>> <<instanceof>>

class Student {

string name;string address;

float gpa;

public void goToClass( ) {

// code here

}

public Student(string argName) {

name = argName;

}

}

Student s1 = new Student(“Chris”);

Student s2 = new Student(“Mike”);

Student s3 = new Student(“Chris”);

Same thing inC#. Notice how concept

maps to code.

Page 19: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 19/48

Classes

Page 20: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 20/48

Classes

• Class Declaration

• public

• The public modifier declares that the class can be

used by any class regardless of its package.

Cl

Page 21: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 21/48

Classes• Class Declaration

• abstract

• Declares that the class cannot be instantiated

• final

• Declares that the class cannot be subclassed.

• class NameOfClass

• The class keyword indicates to the compiler that

this is a class declaration the name of the class isNameOfClass.

• extends Super

• The extends clause identifies Super as the superclass of the class

• implements Interfaces

• Declares that your class implements one or more interfaces

Page 22: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 22/48

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.

Page 23: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 23/48

Classes: Constructors

• All Java classes have constructors that are used toinitialize 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 newobject's state

• The default constructor is automatically provided by theruntime system for any class that contains noconstructors

• Superclass constructor must be the first statement inthe subclass's constructor

Classes: Member variables

Page 24: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 24/48

Classes: Member variables

• Declaration should be within the class body but outside

of any methods or constructors•  private Vector items;

Page 25: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 25/48

Classes: Implementing methods

• A method has two major parts: method

declaration and method body

Page 26: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 26/48

Classes: Implementing methods

• Method declaration

Page 27: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 27/48

Classes: Implementing methods

• Passing information to methods

• Declare the type and name for each argument in the methodsignature

• 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;

}

Cl I l i h d

Page 28: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 28/48

Classes:Implementing methods

• Passing information to methods

• Argument Types

• An argument can be any valid Java data type into a method

• Argument Names

• A method argument can have the same name as one of the class'smember variables

• Pass by Value• Arguments are passed by value .

• primitive type -> pass-by-value means that the method cannot changeits value

• reference type -> pass-by-value means that

• It cannot change the object reference

• It can modify the accessible variables within the object

Classes

Page 29: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 29/48

Classes• Implementing methods

• Method bodyclass 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--];

}

}

}

Page 30: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 30/48

Classes

• Method body

• It may contain declarations for variables that are local to thatmethod

• ‘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

Page 31: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 31/48

Classes• Access Control

• Classes can protect their member variables and methods fromaccess by other objects

• Access specifiers to protect both a class's variables and its

methods•

Specifier Class SubClass

Package

World

Private

Protect

ed

Public

None(Package)

Cl I l ti th d

Page 32: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 32/48

Classes:Implementing methods

• Instance and Class membersInstance variable

Every time you create an instance of a classthe runtime system creates one copy of each class's

instance variables for the instance

Class variables

• The runtime system allocates class variables once per classregardless 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 throughthe class itself

Constructors & Consistent State

Page 33: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 33/48

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();

Page 34: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 34/48

Constructors & Consistent State1. 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);

• } }

Page 35: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 35/48

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

Page 36: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 36/48

Constructors & Consistent State

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

• 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 …• }

Page 37: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 37/48

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 that’s even better…

Constructors & Consistent State

Page 38: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 38/48

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;

• }}

C C i S

Page 39: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 39/48

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

Page 40: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 40/48

• Busting Jargons Getter methods are also known as accessors as

they allow us to access data

Setter methods are also known as mutators as theyallow us to set or mutate data

A class with no mutator methods having all privatedata members with accessors only is known as animmutable class

Classes which have only private data members andthe relevant accessor and mutator methods areknown as POJO (Plain Old Java Object) classes

Q i Cl

Page 41: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 41/48

Quiz:Classes1. Consider the following class:

public class IdentifyMyParts {

public static int x = 7;

public int y = 3;}

a. How many class variables does theIdentifyMyParts class contain? What are theirnames?

b. How many instance variables does theIdentifyMyParts class contain? What are theirnames?

c. What is the output from the following

code:

Q i Cl

Page 42: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 42/48

Quiz:ClassesIdentifyMyParts 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);•

E i Cl

Page 43: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 43/48

Exercises:Classes

• 1. Write a class whose instances represent a playingcard 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 adeck of cards and displaying its cards.

POS Class Exercise

Page 44: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 44/48

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 usingsku as the key

•  Method findItem():• Takes sku and return Item, null if sku is

not found

POS Class Exercise

Page 45: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 45/48

OS C ass e c se 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

• Construct a SaleItem object using theitem above and passed in qty 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

POS Class Exercise

Page 46: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 46/48

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

Page 47: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 47/48

Encapsulation

• Objects should be self contained

 – When you tell a dog to fetch, you do not worry aboutthe details of how he or she does it

 – Objects should encapsulate their implementationdetails 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

Page 48: Lect - OOPS

8/2/2019 Lect - OOPS

http://slidepdf.com/reader/full/lect-oops 48/48

Quiz - Encapsulation

• If you know a subclass will need to access

your classes attributes, is it OK to declarethem as protected?