advance concepts in oop

112
1 unit 8 Advance concepts in OOP Advance concepts in OOP We discuss fundamental object- oriented techniques that supports re-use of software: Interface and polymorphhism Inheritance Method overriding Polymorphism, widening & narrowing protected and final modifiers basic programmin g concepts object oriented programmin g topics in computer science syllabus

Upload: wayde

Post on 12-Jan-2016

72 views

Category:

Documents


6 download

DESCRIPTION

Advance concepts in OOP. We discuss fundamental object-oriented techniques that supports re-use of software: Interface and polymorphhism Inheritance Method overriding Polymorphism, widening & narrowing protected and final modifiers. syllabus. basic programming concepts. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Advance concepts in OOP

1unit 8

Advance concepts in OOPAdvance concepts in OOP

We discuss fundamental object-oriented techniques that supports re-use of software:

• Interface and polymorphhism

• Inheritance

• Method overriding

• Polymorphism, widening & narrowing• protected and final modifiers

basic programming

concepts

object oriented programming

topics in computer science

syllabus

Page 2: Advance concepts in OOP

2unit 8

Principles of object-oriented programmingPrinciples of object-oriented programming

encapsulation: data is protected from “external” users

inheritance: properties and methods defined for a certain structures can be used by all structures defined as direct offspring

polymorphism: the same function call may invoke different code, depending on context

Page 3: Advance concepts in OOP

3unit 8

InterfacesInterfaces

A Java interface is a collection of abstract methods and constants

An abstract method is a method header without a method body An abstract method can be declared using the modifier abstract, but because all methods in an interface are abstract, it is usually left off

An interface is used to formally define a set of methods that a class will implement

Page 4: Advance concepts in OOP

4unit 8

Interface: exampleInterface: example

public interface Doable{

public void doThis;)(

public int doThat;)(

public void doThis2 (float value, char ch);

public boolean doTheOther (int num);}

interface is a reserved wordinterface is a reserved wordNone of the methods in anNone of the methods in an

interface are giveninterface are givena definition )body(a definition )body(

A semicolon immediatelyA semicolon immediatelyfollows each method headerfollows each method header

Page 5: Advance concepts in OOP

5unit 8

InterfacesInterfaces

An interface cannot be instantiated

Methods in an interface are always public and abstract

Constant in an interface are always public, static and final

A class formally implements an interface by• stating so in the class header

• providing implementations for each abstract method in the interface

If a class declares that it implements an interface, it must define all methods in the interface or the compiler will produce errors

Page 6: Advance concepts in OOP

6unit 8

Implementing interface: exampleImplementing interface: example

public class CanDo implements Doable{

public void doThis)( {

// whatever}

public void doThat)( {

// whatever}

// etc.}

implements is aimplements is areserved wordreserved word

Each method listedEach method listedin Doable isin Doable is

given a definitiongiven a definition

Page 7: Advance concepts in OOP

7unit 8

InterfacesInterfaces

A class that implements an interface can implement other methods as well

A class can implement multiple interfaces; the interfaces are listed in the implements clause, separated by commas

The class must implement all methods in all interfaces listed in the header

Page 8: Advance concepts in OOP

8unit 8

Polymorphism via InterfacesPolymorphism via Interfaces

An interface name can be used as the type of an object reference variable

Doable obj;

The obj reference can be used to point to any object of any class that implements the Doable interface

The version of doThis that the following line invokes depends on the type of object that obj is referring to:

obj.doThis();

Page 9: Advance concepts in OOP

9unit 8

Example: Animate InterfaceExample: Animate Interface

************************************// //Animate.java

// //Demonstrates the declaration of an interface

************************************//

public interface Animate{

int HIND_LIMBS_NUM = 2; int FORE_LIMBS_NUM = 2;

public void sound;)( public void gait )String type(;

}

Page 10: Advance concepts in OOP

10unit 8

//Parrot.java

class Parrot implements Animate{

private String word;

----------------------------------// // Establish Parrot's vocabulary

----------------------------------// public Parrot )String word(

{ this.word = word;

}

----------------------------------// // Prints this parrot's sound.

----------------------------------// public void sound)(

{ System.out.println )"This parrot says "

+word;) }

----------------------------------// //Prints this parrot's gait

----------------------------------// public void gait )String gaitType(

{ System.out.println )"Parrots " + gaitType +

" on " + HIND_LIMBS_NUM + " limbs"(;}

}

Page 11: Advance concepts in OOP

11unit 8

//Dog.java

class Dog implements Animate{

private String name; private String owner;

----------------------------------// // Establish Dog's id

----------------------------------// public Dog)(

{ name = "Lassi;" owner = "John;"

}

----------------------------------// // Prints this dog's sound.

----------------------------------// public void sound)(

{ System.out.println )"woof"(;

}

----------------------------------// // Prints this dog's gait

----------------------------------// public void gait )String gaitType(

{ System.out.println )"Dog " + name + " " +

gaitType + " on " + )HIND_LIMBS_NUM+FORE_LIMBS_NUM( + " limbs"(;

}

----------------------------------// // Prints unique contact information

----------------------------------// public void contact)(

{ System.out.println )"If you find me, call " + owner(;

} }

Page 12: Advance concepts in OOP

12unit 8

//Pets.javaclass Pets{-----------------------------------------------------------------//

// Instantiates two objects using an interface reference and invokes one of the common // methods. Then casts interface reference into a class reference to invoke its unique method

-----------------------------------------------------------------// public static void main )String[] args(

{ Animate current;

current = new Parrot)"hello"(; current.sound;)(

current.gait)"walk"(; System.out.println)"***********\n"(;

current = new Dog;)( current.sound;)(

current.gait)"runs"(;

((Dog )current.)contact;)(} }

woofParrots walk on 2 limbs

If you find me, call John

This parrot says hello

Dog Lassi runs on 4 limbs

Page 13: Advance concepts in OOP

13unit 8

Polymorphism via InterfacesPolymorphism via Interfaces

Interface reference is polymorphic, which can be defined as "having many forms"

The corresponding line of code may execute different methods at different times if the object that obj points to changes

Note that polymorphic references must be resolved at run time; this is called dynamic binding

Careful use of polymorphic references can lead to elegant, robust software designs

Page 14: Advance concepts in OOP

14unit 8

Review: Interfaces and Review: Interfaces and polymorphismpolymorphism

A Java interface is a collection of abstract methods and constants; an interface is used to formally define a set of methods that a class will implement

Interface reference is polymorphic, which can be defined as "having many forms"

The corresponding line of code may execute different methods at different times if the object that obj points to changes

Page 15: Advance concepts in OOP

15unit 8

Standard InterfacesStandard Interfaces

The Java standard class library contains many interfaces that are helpful in certain situations

The Comparable interface contains an abstract method called compareTo, which is used to compare two objects

The String class implements Comparable which gives us the ability to put strings in alphabetical order

The Iterator interface contains methods that allow the user to move through a collection of objects easily

Page 16: Advance concepts in OOP

16unit 8

Example: Sorting ObjectsExample: Sorting Objects

Integers have an inherent order, but the order of a set of objects must be defined by the person defining the class

We can use the Comparable interface to develop a generic sort for a set of objects

Page 17: Advance concepts in OOP

17unit 8

class Contact implements Comparable { private String firstName, lastName, phone;

// Uses both last and first names to determine lexical ordering.

public int compareTo )Object other({ int result;

if )lastName.equals)))Contact(other(.lastName(( result = firstName.compareTo)))Contact(other(.firstName(;

else result = lastName.compareTo)))Contact(other(.lastName(;

return result;}

public String toString)( return lastName + ", " + firstName;{

Page 18: Advance concepts in OOP

18unit 8

public class Sorts{ public static void insertionSort )Comparable[] objects({

for )int index = 1; index < objects.length; index++({

Comparable key = objects[index]; int position = index;

// shift larger values to the right while )position > 0 && objects[position-1].compareTo)key( > 0(

{ objects[position] = objects[position-1];

position;--}

objects[position] = key;} } }

Page 19: Advance concepts in OOP

19unit 8

class SortPhoneList{ -----------------------------------------------------------------//

// Creates an array of Contact objects and sorts them-----------------------------------------------------------------//

public static void main )String[] args({

Contact[] friends = new Contact[4];

friends[0] = new Contact )"John", "Smith", "610-555-7384"(; friends[1] = new Contact )"Daphna", "Weinshall", "02-555-7777"(; friends[2] = new Contact )"Moshe", "Cohen", "03-222-3333"(; friends[3] = new Contact )"Marsha", "Grant", "243-555-2837"(;

Sorts.insertionSort)friends(; for )int i=0; i<friends.length; ++i(

System.out.println)friends[i](; {}

Page 20: Advance concepts in OOP

20unit 8

Unit 8Unit 8

Interface and polymorphhism Inheritance Method overriding Polymorphism, widening & narrowing protected and final modifiers

Page 21: Advance concepts in OOP

21unit 8

InheritanceInheritance

Inheritance allows us to derive a new class from an existing one:• The existing class is called the superclass or base-class

• The derived class is called the subclass or derived-class

Instances of the derived class inherit all the properties and functionality )data and methods( defined in the base class

Usually, the derived class adds more functionality and properties

Page 22: Advance concepts in OOP

22unit 8

ExampleExample

Employee

Employee (String name, ...

hire(double payRate)

pay()layoff()

promote()

...

Hourly

Hourly()

addHours(int moreHours)

Executive

Executive()

giveBonus(int bonus)

Page 23: Advance concepts in OOP

23unit 8

Properties of subclassProperties of subclass

Everything that can be done with an Employee object can also be done with an Hourly object

An Hourly is a special kind of Employee; it has all the functionality of an employee and some more

The subclass instances are more specific than the instances of the superclass

Page 24: Advance concepts in OOP

24unit 8

Example: the Employee classExample: the Employee class

public class EmployeeEmployee {

private String name; private String address; private double payRate;

public Employee (String name, String address) { this.name = name; this.address = address; payRate = 0; }

public void hire (double payRate) { this.payRate = payRate; }

public double pay () { return(payRate); }}

public void layoff () { payRate = 0;}

Page 25: Advance concepts in OOP

25unit 8

Subclass: the Subclass: the extendsextends Keyword Keyword

// define a special kind of employee - LEFI SHAOT

public class HourlyHourly extends Employee {

private int hoursWorked;

public void addHours (int moreHours) { hoursWorked += moreHours; }

public double pay () { return payRate*hoursWorked; } }

Page 26: Advance concepts in OOP

26unit 8

More about subclassMore about subclass

Derived class should normally extend the functionality of the superclass

In certain cases, a derived class would change some of the functionality of the superclass

Page 27: Advance concepts in OOP

27unit 8

The The hourly hourly subclasssubclass

// define a special kind of employee - LEFI SHAOT

public class HourlyHourly extends Employee {

private int hoursWorked;

public void addHours (int moreHours) { hoursWorked += moreHours; }

public void pay () { return payRate*hoursWorked; }

}

extend

change

Page 28: Advance concepts in OOP

28unit 8

ExamplesExamples

Point

Pixel

Employee

Hourly

Object

File

RestrictedFile

Switch

AdjustableSwitch

Page 29: Advance concepts in OOP

29unit 8

What is InheritedWhat is Inherited??

The subclass inherits:• all the fields of the base class• all the methods of the base class

The constructors of the subclass should be defined again

Private fields and methods are inherited but cannot be accessed directly from the code of the subclass; they can only be accessed indirectly

Page 30: Advance concepts in OOP

30unit 8

Switch

isOn

Switch() boolean isOn() setOn(boolean)

SwitchSwitch Example Example

Page 31: Advance concepts in OOP

31unit 8

SwitchSwitch Code Code

// An electronic switch that can be on/off

public class SwitchSwitch {

// Records the state of the switch private boolean isOn;

// Checks if this switch is on public boolean isOn() { return isOn;

}

// Sets the state of the switch on/off public void setOn(boolean state) { isOn = state; }}

Page 32: Advance concepts in OOP

32unit 8

Special type: Adjustable SwitchSpecial type: Adjustable Switch

on off

pressing the adjustable switch

turns it on

an adjustable switch has

a “level of current” dial

Page 33: Advance concepts in OOP

33unit 8

Inheriting Inheriting AdjustableSwitchAdjustableSwitch from from SwitchSwitch

Switch

AdjustableSwitch

Switch() isOn() setOn(boolean)

AdjustableSwitch() setLevel(float) getLevel()

Page 34: Advance concepts in OOP

34unit 8

AdjustableSwitch

AdjustableSwitchAdjustableSwitch Example Example

setOn(boolean) isOn()

isOn

level

AdjustableSwitch() setLevel(float) getLevel()

Page 35: Advance concepts in OOP

35unit 8

AdjustableSwitchAdjustableSwitch Code Code

public class AdjustableSwitchAdjustableSwitch extends Switch {

// The level of current (0-100) private float level;

// Sets the level of current public void setLevel(float level) { this.level = level; }

// Returns the level of current of the switch public float getLevel() { return level; }

}

Page 36: Advance concepts in OOP

36unit 8

Private Fields - Inherited but not AccessiblePrivate Fields - Inherited but not Accessible

An AdjustableSwitch object has a state variable isOn inherited from Switch

However, it cannot be accessed directly from the code of AdjustableSwitch because it is defined as private in Switch )it is encapsulated(

Page 37: Advance concepts in OOP

37unit 8

Inheritance: a Basis for Code ReusabilityInheritance: a Basis for Code Reusability

Fast implementation - we need not write the implementation of AdjustableSwitch from scratch, we just implement the additional functionality

Ease of use - if someone is already familiar with the base class, then the derived class will be easy to understand

Less debugging - debugging is restricted to the additional functionality

Ease of maintenance - if we need to correct/improve the implementation of Switch, AdjustableSwitch is automatically corrected as well

Compactness - our code is more compact and is easier to understand

Page 38: Advance concepts in OOP

38unit 8

Example: Changing the Base ClassExample: Changing the Base Class

Suppose that we want to add the property of ‘maximal power’ to our representation of a switch

This property is suitable in adjustable switches as well )the inheritance supports our abstraction!(

Inheritance allows us to add this property only in the base class; the changes will automatically take place in the inherited class

Page 39: Advance concepts in OOP

39unit 8

Changing the Changing the SwitchSwitch Class Class

public class SwitchSwitch {

// Records the state of the switch private boolean isOn;

// The maximal power of this switch private float maxPower;

// constructor public Switch(float maxPower) { if (maxPower > 0.0f) this.maxPower = maxPower; }

// Returns the maximal power of this switch public float getMaxPower() { return maxPower; }}

Page 40: Advance concepts in OOP

40unit 8

Constructors of subclasses must Constructors of subclasses must be redefinedbe redefined??

The constructor of Switch receives a parameter - maxPower - and initializes the private field with the same name

We have to define a constructor for AdjustableSwitch that receives the same parameter and initializes this field; but this field is private, so there is no direct access to it

In general, when we invoke a constructor of a subclass, we first have to construct the superclass “part” of the subclass; we do this by using the super keyword

Page 41: Advance concepts in OOP

41unit 8

// Constructs an adjustable switch public AdjustableSwitch(float power) { super(power); }

The first line of the constructor calls the constructor of the superclass )Switch( that receives a float parameter to

initialize the state variable defined in the superclass

AdjustableSwitchAdjustableSwitch - Redefinition of Constructor - Redefinition of Constructor

Page 42: Advance concepts in OOP

42unit 8

Calling Calling supersuper)...()...(

The constructor of a derived class MUST initialize the state of the object from the point of view of its parent class

the first line in the constructor must be a call to one of the constructors in the superclass using super)...(

Otherwise, the compiler automatically places a call to the empty constructor of the superclass

A later call to super)...( is not allowed because a constructor can be invoked only once

Page 43: Advance concepts in OOP

43unit 8

Automatic Default ConstructionAutomatic Default Construction

In the previous implementation of Switch and AdjustableSwitch we did not include any constructors

The compiler automatically adds an empty )default( constructor to each of the classes

In addition, the compiler puts in the first line of the empty constructor of AdjustableSwitch a call to the empty constructor of Switch

Page 44: Advance concepts in OOP

44unit 8

Automatic Default ConstructionAutomatic Default Construction

// ...in class Switch (automatically added)

public Switch() {}

// and in class AdjustableSwitch //(automatically added)

public AdjustableSwitch() { super();}

Page 45: Advance concepts in OOP

45unit 8

Default Construction Using Other ConstructorsDefault Construction Using Other Constructors

Sometimes the programmer may wish to define a default constructor )i.e., a constructor with no arguments( by herself, which may call other constructors with default arguments of her choice

If we do this in the Switch class, we need not define any constructor in the AdjustableSwitch class

Page 46: Advance concepts in OOP

46unit 8

Default Construction - DelegationDefault Construction - Delegation

// Constructs a new switch. // @param power the maximal power of the switch public Switch(float maxPower) { if (maxPower > 0.0f) this.maxPower = maxPower; }

private static final DEFAULT_POWER = 60.0f;

// Constructs a switch with default power public Switch() { this(DEFAULT_POWER); }

Page 47: Advance concepts in OOP

47unit 8

Unit 8Unit 8

Interface and polymorphhism Inheritance Method overriding Polymorphism, widening & narrowing protected and final modifiers

Page 48: Advance concepts in OOP

48unit 8

Overriding MethodsOverriding Methods

Occassionally, when we derive a class, we want to change some of the functionality defined in the superclass

Mechanism: a sub-class can override the definition of an inherited method in favor of its own

That is, a child can redefine a method that it inherits from its parent; the new method must have the same signature as the parent's method, but can have different code

The type of the object executing the method determines which version of the method is invoked

Page 49: Advance concepts in OOP

49unit 8

File

File(String name) isOpen() open() close() getName()

RestrictedFile

RestrictedFile(String name, long key) isLocked() lock() unlock(long key)

Overriding: exampleOverriding: example

we want clients to be able to open a restricted file only if it is unlocked; how do we do it?

Page 50: Advance concepts in OOP

50unit 8

FileFile Example Example

public class FileFile { // The name of the file private String name; // true if the file is opened private boolean isOpen;

// Construct a file with a given name public File(String name) { this.name = name; }

// Returns the name of the file public String getName() { return name; }

Page 51: Advance concepts in OOP

51unit 8

FileFile Example Example

// Checks if the file is open public boolean isOpen() { return isOpen; }

// Opens the file public void open() { // … other operations isOpen = true; } // Closes the file public void close() { // … other operations isOpen = false; }}

Page 52: Advance concepts in OOP

52unit 8

RestrictedFileRestrictedFile Example Example

// Represents a restricted file, which can be opened only// if unlocked; in order to unlock the file, key is neededpublic class RestrictedFile RestrictedFile extends File { // Password for unlocking the file private long key;

// The state of the file - locked/unlocked private boolean isLocked;

// Constructs a new restricted file public RestrictedFile(String name, long key) { super(name); this.key = key; isLocked = true; }

Page 53: Advance concepts in OOP

53unit 8

RestrictedFileRestrictedFile: added methods: added methods

// Checks if the file is locked public boolean isLocked() { return isLocked; } // Locks the file public void lock() { isLocked = true; }

// Unlock the file; the file will be unlocked only // if the given key is valid public void unlock(long key) { if (this.key == key) { isLocked = false; } }

So far the implementation is useless if we do not change the implementation of open()

Page 54: Advance concepts in OOP

54unit 8

Method overridingMethod overriding

// Open the file - file will be opened // only if it is unlocked

public void open() { if (!isLocked()) { super.open(); } }

Page 55: Advance concepts in OOP

55unit 8

Overriding in Overriding in RestrictedFileRestrictedFile

RestrictedFile inherits the interface of File, but changes the functionality of the method open()

We say that RestrictedFile overrides the method open()

Note the call to super.open() - we invoke the method open() of the superclass on this object

Page 56: Advance concepts in OOP

56unit 8

Rules of InheritanceRules of Inheritance

When class B is derived from a class A, the interface of class B will be a superset of that of class A )except for constructors(

It is not possible to remove a method from the interface by subclassing

However, class B can override some of the methods that it inherits and thus change their functionality

Page 57: Advance concepts in OOP

57unit 8

Rules of OverridingRules of Overriding

When overriding a method, a parent method can be explicitly invoked using the super reference

If a method is declared with the final modifier, it cannot be overridden

The concept of overriding can be applied to data )called shadowing variables(, but there is generally no need for it

Page 58: Advance concepts in OOP

58unit 8

Overloading vs. OverridingOverloading vs. Overriding

Overloading deals with multiple methods in the same class with the same name but different signatures

Overloading lets you define a similar operation in different ways for different input data )different parameters(

Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature

Overriding lets you define a similar operation in different ways for different object types

Page 59: Advance concepts in OOP

59unit 8

Unit 8Unit 8

Interface and polymorphhism Inheritance Method overriding Polymorphism, widening & narrowing protected and final modifiers

Page 60: Advance concepts in OOP

60unit 8

Class HierarchiesClass Hierarchies

A child class of one parent can be the parent of another child, forming class hierarchies

StaffMember

Employee

Hourly Executive Sherut Leumi

Volunteer

Page 61: Advance concepts in OOP

61unit 8

Class HierarchiesClass Hierarchies

Two children of the same parent are called siblings

Good class design puts all common features as high in the hierarchy as is reasonable

An inherited member is continually passed down the line

Class hierarchies often have to be extended and modified to keep up with changing needs

Page 62: Advance concepts in OOP

62unit 8

The The ObjectObject Class Class

A class called Object is defined in the java.lang package of the Java standard class library

All classes are derived from the Object class

If a class is not explicitly defined to be the child of an existing class, it is assumed to be the child of the Object class

The Object class is therefore the ultimate root of all class hierarchies

Page 63: Advance concepts in OOP

63unit 8

The The ObjectObject Class Class

The Object class contains a few useful methods, which are inherited by all classes

For example, the equals method of the Object class determines if two references are aliases

When you define a new class, you can override equals to define equality in some other way

Page 64: Advance concepts in OOP

64unit 8

The The ObjectObject Class Class

The toString method is defined in the Object class: it returns a string that contains the name of the object’s class and a hash value

That’s why the println method can call toString for any object that is passed to it – all objects are guaranteed to have a toString method via inheritance

When we define a new class, we can override the toString() method in order to have a suitable representation of the new type of objects as Strings

Page 65: Advance concepts in OOP

65unit 8

Example of Example of OverridingOverriding toStringtoString)()(

// Represents a point on a gridpublic class PointPoint { // The coordinates of the point private int x,y;

// Constructs a new point public Point(int x, int y) { this.x = x; this.y = y; }

public String toString() { return “(“ + x + ”,” + y + ”)”; }

Page 66: Advance concepts in OOP

66unit 8

Example of Overriding Example of Overriding toStringtoString)()(

// Example: overriding the toString() method

class PrintingPointExamplePrintingPointExample {

public static void main(String[] args) {

Point p = new Point(2,3);

System.out.println(p);

//System.out.println(p.toString());

}

}

Page 67: Advance concepts in OOP

67unit 8

Class Hierarchy: exampleClass Hierarchy: example

File

Object

RestrictedFile

a RestrictedFile is-a File which is-a Object

Page 68: Advance concepts in OOP

68unit 8

Reference and InheritanceReference and Inheritance

We can view a RestrictedFile object from 3 different points of views:

• As a RestrictedFile: this is the most narrow point of view )the most specific(; this point of view ‘sees’ the full functionality of the object

• As a File: this is a wider point of view )a less specific one(; this point of view is ‘ignorant’ of the special characteristics the object has as a RestrictedFile )we can only open and close the file(

• As an plain Object

Page 69: Advance concepts in OOP

69unit 8

11 Object reference, many typesObject reference, many types

We view an object by using an object reference

A variable of type ‘reference to File’ can only refer to an object which is a File: File f = new File(“story.txt”);

But a RestrictedFile is also a File, so f can also refer to a RestrictedFile object: File f = new RestrictedFile(“visa.dat”);

The type of the reference we use determines the point of view we will have on the object

Page 70: Advance concepts in OOP

70unit 8

Point of View 1Point of View 1

RestrictedFile f = new RestrictedFile(“visa.dat”, 12345);

f.close(); f.lock(); f.unlock(12345); String s = f.toString();

If we refer to a RestrictedFile object using a RestrictedFile reference, we have the RestrictedFile point of view - we see all the methods that are defined in RestrictedFile and up the hierarchy:

Page 71: Advance concepts in OOP

71unit 8

Point of View 2Point of View 2

File f = new RestrictedFile((“visa.dat”, 12345);

f.close(); f.lock(); f.unlock(12345); String s = f.toString();

If we refer to a RestrictedFile object using a File reference, we have the File point of view – we see only methods that are defined in class File and up the hierarchy tree:

Page 72: Advance concepts in OOP

72unit 8

Point of View 3Point of View 3

Object f = new RestrictedFile((“visa.dat”, 12345);

f.close(); f.lock(); f.unlock(12345); String s = f.toString();

If we refer to a RestrictedFile object using an Object reference, we have the Object point of view - we see only methods that are defined in class Object:

Page 73: Advance concepts in OOP

73unit 8

VisualizationVisualization

RestrictedFile

... isOpen isLocked key

toString() ... isOpen() open() close() lock() unlock(key) isLocked()

file

object

restricted file

Page 74: Advance concepts in OOP

74unit 8

References and InheritanceReferences and Inheritance

An object reference can refer to an object of its class, or to an object of any descendant class related to it by inheritance

Assigning a child object to an ancestral reference is considered to be a widening conversion, and can be performed by simple assignment

Assigning an object with ancestral reference to a child reference can also be done, but it is considered to be a narrowing conversion and must be done with an explicit cast

Page 75: Advance concepts in OOP

75unit 8

RestrictedFile referenceRestrictedFile point of view

File referenceFile point of view

Widening

WideningWidening

Changing our point of view of an object to a wider one )a less specific one( is called widening:File file;

file = new RestrictedFile((“visa”, 1234);

Page 76: Advance concepts in OOP

76unit 8

PointPoint class example class example

// A point on a gridpublic class PointPoint { // ... The same implementation as before

// Computes the distance from another point // @param p: the given point public double distanceFrom(Point p) { int dx = x-p.x; int dy = y-p.y; return Math.sqrt(dx*dx+dy*dy); }

// ... more methods}

Page 77: Advance concepts in OOP

77unit 8

PixelPixel subclass example subclass example

// Represents a pixel on a graphical areapublic class PixelPixel extends Point { // The color of the pixel private Color color;

// Constructs a new pixel public Pixel(int x, int y, Color color) { super(x,y); this.color = color; }

// ... more methods}

Page 78: Advance concepts in OOP

78unit 8

WideningWidening

In the following example, the method distanceFrom() expects a ‘reference to Point’ and gets ‘a reference to Pixel’; we are thus widening our point of view of the Pixel object

Pixel p1, p2;

p1 = new Pixel(2, 3, Color.yellow);

p2 = new Pixel(5, 6, Color.red);

double d = p1.distanceFrom(p2);

Page 79: Advance concepts in OOP

79unit 8

NarrowingNarrowing

If we look at all objects from a wide point of view, and would not be able to restore a more narrow view for some of them, there is little point in having multiple points of view

We can restore the narrow point of view for objects by casting

We can use the instanceof operator to query about the type of the object we are referencing

Page 80: Advance concepts in OOP

80unit 8

Narrowing ExampleNarrowing Example

// Locks all the restricted files in the array // @param files: the array of files to be locked

public static void lockRestrictedFiles(File[] files) {

for (int i = 0; i < files.length; i++) { if (files[i] instanceof RestrictedFile) { RestrictedFile file = (RestrictedFile)files[i]; file.lock(); } }}

RestrictedFile point of view File point of view

Narrowing

Page 81: Advance concepts in OOP

81unit 8

Narrowing - Equivalent ExampleNarrowing - Equivalent Example

// Locks all the protected files in the array // @param files The array of files to be locked

public static void lockRestrictedFiles(File[] files) { for (int i = 0; i < files.length; i++) { if (files[i] instanceof RestrictedFile) { ((RestrictedFile)files[i]).lock(); } }}

Page 82: Advance concepts in OOP

82unit 8

Rules of NarrowingRules of Narrowing

Narrowing lets us restore a more specific point of view of an object

You cannot refer to an object through a RestrictedFile reference unless this object is indeed a RestrictedFile object

If we try to cast a File reference to RestrictedFile and the former reference refers to a regular File, we will get the error message ClassCastException

In the previous example we cast the reference only after we verified the object is indeed a RestrictedFile

Page 83: Advance concepts in OOP

83unit 8

Polymorphism via InheritancePolymorphism via Inheritance

We saw how an interface can be used to create a polymorphic reference

Recall that a polymorphic reference is one which can refer to different types of objects at different times

Inheritance can also be used as a basis of polymorphism

An object reference can refer to one object at one time, then it can be changed to refer to another object )related by inheritance( at another time

Page 84: Advance concepts in OOP

84unit 8

Polymorphism via Inheritance: examplePolymorphism via Inheritance: example

Suppose the Employee class has a method called pay, and the Hourly class overrode it

Now consider the following invocation:

Daphna.pay();

If Daphna refers to a Employee object, it invokes the Employee version of pay; if it refers to a Hourly object, it invokes the Hourly version

Page 85: Advance concepts in OOP

85unit 8

Polymorphism via InheritancePolymorphism via Inheritance

It is the type of the object being referenced, not the reference type, that determines which method is invoked

Note that, if an invocation is in a loop, the exact same line of code could execute different methods at different times

Polymorphic references are therefore resolved at run-time, not during compilation

Page 86: Advance concepts in OOP

86unit 8

Type of Method is Determined at Type of Method is Determined at Runtime (1)Runtime (1)

File file;

if (Math.random() >= 0.5) { file = new File();}else { file = new RestrictedFile(“visa.dat”, 76543); // Recall that a RestrictedFile is locked by // default}file.open();

Will the file be opened if the number tossed is less than 0.5 ??

Page 87: Advance concepts in OOP

87unit 8

Type of Method is Determined at Type of Method is Determined at Runtime (2)Runtime (2)

public void workaroundAttempt(RestrictedFile file) {

File workaroundReference = file;

workaroundReference.open();

// }

Since the file is of type RestrictedFile, this will invoke open)( which is defined on restricted files and not on regular files

will the file be opened?

Page 88: Advance concepts in OOP

88unit 8

Heterogeneous CollectionsHeterogeneous Collections

Polymorphism is especially useful when we want to create a heterogeneous collection of objects

Example: a class Staff that represents all workers in a certain organization, some of whom are employees and some are volunteers

Among the employees: some are regular employees paid monthly, some are temporary and are paid by the hour, while some are managers )executives( and get bonuses

Page 89: Advance concepts in OOP

89unit 8

Example: StaffMember Class HierarchyExample: StaffMember Class Hierarchy

StaffMember

Employee Volunteer

Hourly Executive

Page 90: Advance concepts in OOP

90unit 8

StaffMember classStaffMember class

// StaffMember.javaclass StaffMemberStaffMember{ private String name; private String address; private String phone;

// constructor public StaffMember (String name, String address, String phone)

{ this.name = name; this.address = address; this.phone = phone; }

public double pay(){return 0.0;

}}

Page 91: Advance concepts in OOP

91unit 8

Volunteer subclassVolunteer subclass

// Volunteer.javaclass VolunteerVolunteer extends StaffMember { // constructor public Volunteer (String name, String address,

String phone) { super (name, address, phone); }

// override method public double pay () { return 0.0; }}

Page 92: Advance concepts in OOP

92unit 8

Employee subclassEmployee subclass

// Employee.javaclass EmployeeEmployee extends StaffMember{ private double payRate; // constructor public Employee (String name, String address, String

phone, double payRate) { super (name, address, phone); this.payRate = payRate; } // override method public double pay () { return payRate; }}

Page 93: Advance concepts in OOP

93unit 8

Hourly subclass of EmployeeHourly subclass of Employee

// Hourly.javaclass HourlyHourly extends Employee{ private int hoursWorked;

// constructor public Hourly (String name, String address, String phone,

double payRate) { super (name, address, phone, payRate); hoursWorked = 0; }

// unique method public void addHours (int moreHours) { hoursWorked += moreHours; } …

Page 94: Advance concepts in OOP

94unit 8

Hourly subclass of Employee (cont)Hourly subclass of Employee (cont)

//---------------------------------------------- // override method pay of Employee: Compute // and return the pay for this hourly employee //--------------------------------------------- public double pay () { double payment = payRate * hoursWorked; hoursWorked = 0;

return payment; }}

Page 95: Advance concepts in OOP

95unit 8

Executive subclass of EmployeeExecutive subclass of Employee

// Executive.javaclass ExecutiveExecutive extends Employee{ private double bonus;

// constructor public Executive (String name, String address, String

phone, double payRate) { super (name, address, phone, payRate); bonus = 0; // bonus has yet to be awarded }

// unique method public void awardBonus (double execBonus) { bonus = execBonus; } …

Page 96: Advance concepts in OOP

96unit 8

Executive subclass of Employee (cont)Executive subclass of Employee (cont)

//----------------------------------------------- // override method pay of Employee: Compute and // return the pay for an executive, which is the // regular employee payment plus a one-time bonus //----------------------------------------------- public double pay () { double payment = super.pay() + bonus; bonus = 0;

return payment; }}

Page 97: Advance concepts in OOP

97unit 8

Heterogeneous collectionsHeterogeneous collections

Suppose we would like to store personnel of all kinds in a single array, so we can easily write code that takes care of all the workers

For example, suppose we want to implement a method getTotalCost() in class Staff that will compute how much money is needed to pay all personnel at the end of the month

Page 98: Advance concepts in OOP

// Staff.javaclass StaffStaff{ StaffMember[] staffList;

// constructor: sets up the list of staff members. public Staff () { staffList = new StaffMember[4];

staffList[0] = new Executive (”Carla", "123 Main Line", "555-0469", 1923.07);

staffList[1] = new Employee ("Sam", "456 Off Line", "555-0101", 846.15);

staffList[2] = new Hourly ("Diane", "678 Fifth Ave.", "555-0690", 8.55);

staffList[3] = new Volunteer ("Norm", "987 Suds Blvd.", "555-8374");

((Executive)staffList[0]).awardBonus (5000.00); ((Hourly)staffList[2]).addHours (40); }

wid

enin

g‹—

—›

narr

owin

g‹—

—›

Page 99: Advance concepts in OOP

We do not care if staffList[count] refers to a Volunteer, a regular Employee, an Hourly or an Executive; they all “know” how to compute their pay

// compute payday costs

public void getTotalCost () { double amount = 0.0;

for (int count=0; count < staffList.length; count++) { amount += staffList[count].pay(); // polymorphic } }

}

Page 100: Advance concepts in OOP

100unit 8

Unit 8Unit 8

Interface and polymorphhism Inheritance Method overriding Polymorphism, widening & narrowing protected and final modifiers

Page 101: Advance concepts in OOP

101unit 8

The The protectedprotected Modifier Modifier

Any class member )variable, method or constructor( can be declared with one of the 4 visibility modifiers: • private - only code of the same class in which the

member has been defined can access this member• )none( - default visibility; only code of a class of the same

package as that of the class in which the member has been defined can access it

• protected - code in a class that is in the same package or is a subclass of the class in which the member was defined

• public - code of any class that can access the class of that member

We declare variables as protected if they will be used often by someone deriving our class, but we still want to hide them from a user of our class

Page 102: Advance concepts in OOP

102unit 8

Class 2Class 1

SubClass 1int a;

public int b;

protected int c;

private int d;

package 1

ok

ok

ok

nono

ok

ok

ok

Class 2Class 1

SubClass 1int a;

public int b;

protected int c;

private int d;

package 1

no

ok

ok

nono

no

ok

no

package 3 package 2

Page 103: Advance concepts in OOP

103unit 8

PointPoint: Example of a : Example of a protectedprotected Field Field

public class PointPoint { // The coordinates of the point protected int x,y;

// constructor public Point(int x, int y) { this.x = x; this.y = y; }

// ...}

Page 104: Advance concepts in OOP

104unit 8

Protected Fields ExampleProtected Fields Example

public class PixelPixel extends Point { // The color of the pixel private Color color; // constructor public Pixel(int x, int y, Color color) { super(x,y); this.color = color; }

// Draws this pixel public void draw() { this method will need to refer to x,y and it will be cumbersome to do this through access methods }}

Page 105: Advance concepts in OOP

105unit 8

The The finalfinal modifier modifier

A final class can not have derived classes

A final method cannot be overriden

A final variable can be initialized only once• If the variable is static you must specify its value in the

declaration and it becomes a constant

• If it is a state variable, you should either specify a value in the declaration or in the constructor, but only there and only once

The final modifier can be used for classes, methods and variables; in each case it has a different meaning:

Page 106: Advance concepts in OOP

106unit 8

Heterogeneous Collections in the Heterogeneous Collections in the Java APIJava API

library class: java.util.Vector

A vector is an oredered collection of objects

You may add or remove objects from the vector at any position

The size of a Vector grows and shrinks as needed to accommodate adding and removing items after the Vector has been created

Page 107: Advance concepts in OOP

107unit 8

Heterogeneous Collections: Heterogeneous Collections: VectorVector

class CatCat { public String toString() { return new String(“meaw”); }}class DogDog { public String toString() { return new String(“bark”); }}class MouseMouse { public String toString() { return new String(“squeak”); }}

Page 108: Advance concepts in OOP

108unit 8

Heterogeneous Collections: Heterogeneous Collections: VectorVector

class MouseTrap MouseTrap { public static void main(String[] args) { Vector v = new Vector(); v.addElement(new Cat()); v.addElement(new Mouse()); v.addElement(new Dog()); v.addElement(new Mouse()); v.addElement( new String(“it’s raining cats and dogs”)); for (int i = 0; i < v.size(); i++) System.out.println(v.elementAt(i)); catchTheMice(v); }

Page 109: Advance concepts in OOP

109unit 8

Heterogeneous Collections: Heterogeneous Collections: VectorVector

private static catchTheMice(Vector v) {

int i = 0;

while (i < v.size())

if (v.elementAt(i) instanceof Mouse) {

v.removeElementAt(i);

}

else {

i++;

}

}

}

Page 110: Advance concepts in OOP

110unit 8

Employee

Executive Visitor

But there can be visitors who are executives as well,

so what do we do in this case?

Multiple Inheritance: MotivationMultiple Inheritance: Motivation

Suppose we want to add a new kind of employee – a visitor

Page 111: Advance concepts in OOP

111unit 8

Single vs. Multiple InheritanceSingle vs. Multiple Inheritance

We would like to define a VisitingExecutive class that extends both Executive and Visitor

Multiple inheritance allows a class to be derived from two or more classes, inheriting the members of all parents; collisions, such as the same variable name in two parents, have to be resolved

Java supports single inheritance, meaning that a derived class can have only one parent class )C++ supports multiple inheritance(

In most cases, the use of interfaces gives us the best aspects of multiple inheritance without the overhead

Page 112: Advance concepts in OOP

112unit 8

Interface HierarchiesInterface Hierarchies

Inheritance can be applied to interfaces as well as classes

One interface can be used as the parent of another

The child interface inherits all abstract methods of the parent

A class implementing the child interface must define all methods from both the parent and child interfaces

Note that class hierarchies and interface hierarchies are distinct )the do not overlap(