Comp 249 Programming Methodology Chapter 8 - Polymorphism Dr. Aiman Hanna Department of Computer...

25
Comp 249 Programming Methodology Chapter 8 - Polymorphism Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal, Canada These slides has been extracted, modified and updated from original slides of Absolute Java 3 rd Edition by Savitch; which has originally been prepared by Rose Williams of Binghamton University. Absolute Java is published by Pearson Education / Addison-Wesley. Copyright © 2007 Pearson Addison-Wesley Copyright © 2013 Aiman Hanna All rights reserved

Transcript of Comp 249 Programming Methodology Chapter 8 - Polymorphism Dr. Aiman Hanna Department of Computer...

Comp 249 Programming Methodology

Chapter 8 - Polymorphism

Dr. Aiman HannaDepartment of Computer Science & Software Engineering

Concordia University, Montreal, Canada

These slides has been extracted, modified and updated from original slides of Absolute Java 3 rd Edition by Savitch; which has originally been prepared by Rose Williams of Binghamton University. Absolute Java is published by

Pearson Education / Addison-Wesley.

Copyright © 2007 Pearson Addison-WesleyCopyright © 2013 Aiman Hanna

All rights reserved

Introduction to Introduction to PolymorphismPolymorphism

There are three main programming There are three main programming mechanisms that constitute object-mechanisms that constitute object-oriented programming (OOP) oriented programming (OOP) EncapsulationEncapsulation InheritanceInheritance PolymorphismPolymorphism

Polymorphism is the ability to associate Polymorphism is the ability to associate many meanings to one method namemany meanings to one method name It does this through a special mechanism It does this through a special mechanism

known as known as late bindinglate binding or or dynamic bindingdynamic binding

8-2

Introduction to Introduction to PolymorphismPolymorphism

Inheritance allows a base class to be Inheritance allows a base class to be defined, and other classes derived from itdefined, and other classes derived from it Code for the base class can then be used for Code for the base class can then be used for

its own objects, as well as objects of any its own objects, as well as objects of any derived classesderived classes

Polymorphism allows changes to be made Polymorphism allows changes to be made to method definitions in the derived to method definitions in the derived classes, classes, and have those changes apply to and have those changes apply to the software writtenthe software written for the base classfor the base class

8-3

Late BindingLate Binding The process of associating a method The process of associating a method

definitiondefinition with a method with a method invocationinvocation is is called called bindingbinding

If the method definition is associated with If the method definition is associated with its invocation when the code is compiled, its invocation when the code is compiled, that is called that is called early bindingearly binding

If the method definition is associated with If the method definition is associated with its invocation when the method is invoked its invocation when the method is invoked (at run time), that is called (at run time), that is called late bindinglate binding or or dynamic bindingdynamic binding

8-4

Late BindingLate Binding Java uses late binding for all methods Java uses late binding for all methods

(except private, (except private, finalfinal,, and static and static methods)methods)

Because of late binding, a method can be Because of late binding, a method can be written in a base class to perform a task, written in a base class to perform a task, even if portions of that task aren't yet even if portions of that task aren't yet defineddefined

See Polymorphism1.javaSee Polymorphism1.java

8-5

Pitfall: No Late Binding for Static Pitfall: No Late Binding for Static MethodsMethods

When the decision of which definition of a When the decision of which definition of a method to use is made at compile time, that is method to use is made at compile time, that is called called static bindingstatic binding This decision is made based on the This decision is made based on the type of the type of the

variable naming the objectvariable naming the object Java uses static, not late, binding with private, Java uses static, not late, binding with private, finalfinal, and static methods, and static methods In the case of In the case of privateprivate and and finalfinal methods, late methods, late

binding would serve no purpose (these methods binding would serve no purpose (these methods cannot be overridden, so only one version exists)cannot be overridden, so only one version exists)

(Warning:)(Warning:) However, in the case of a However, in the case of a staticstatic method method invoked using a calling object, it does make a invoked using a calling object, it does make a differencedifference

See Polymorphism2.javaSee Polymorphism2.java

8-6

Pitfall: No Late Binding for Static Pitfall: No Late Binding for Static MethodsMethods

Example (Example (See Polymorphism2.javaSee Polymorphism2.java): ): The The Vehicle Vehicle class class DisplayNumberOfCreatedObjectsDisplayNumberOfCreatedObjects

()() method: method:public static void DisplayNumberOfCreatedObjects()public static void DisplayNumberOfCreatedObjects()

{{

System.out.println("The number of created Vehicle objects so System.out.println("The number of created Vehicle objects so far is " + numOfCreatedObjects + ".");far is " + numOfCreatedObjects + ".");

}} The The Bus Bus class class DisplayNumberOfCreatedObjectsDisplayNumberOfCreatedObjects ()()

method:method:public static void DisplayNumberOfCreatedObjects()public static void DisplayNumberOfCreatedObjects()

{{

System.out.println("The number of created Bus objects so far System.out.println("The number of created Bus objects so far is " + numOfCreatedObjects + ".");is " + numOfCreatedObjects + ".");

}}

8-7

Pitfall: No Late Binding for Static Pitfall: No Late Binding for Static MethodsMethods

Example (Example (See Polymorphism2.javaSee Polymorphism2.java) – ) – Continues: Continues:

In the previous example, the object In the previous example, the object v1 v1 was created from the was created from the Vehicle Vehicle class, and class, and the object the object b1 b1 was created from the was created from the Bus Bus class,class,

Given the following assignment:Given the following assignment:v1 = b1;v1 = b1;

Now the two variables point to the same objectNow the two variables point to the same object

8-8

Pitfall: No Late Binding for Static Pitfall: No Late Binding for Static MethodsMethods

Example (Example (See Polymorphism2.javaSee Polymorphism2.java) – ) – Continues: Continues:

Given the invocations:Given the invocations:v1.v1.DisplayNumberOfCreatedObjectsDisplayNumberOfCreatedObjects();();b1.b1.DisplayNumberOfCreatedObjectsDisplayNumberOfCreatedObjects();();

The output is:The output is:The number of created Vehicle objects so far is 11.The number of created Vehicle objects so far is 11.

The number of created Bus objects so far is 3.The number of created Bus objects so far is 3.

Note that here, Note that here, DisplayNumberOfCreatedObjects DisplayNumberOfCreatedObjects is a is a static method invoked a calling object (i.e. v1, b1) static method invoked a calling object (i.e. v1, b1) (instead of its class name)(instead of its class name) Therefore the exact executed method is determined by Therefore the exact executed method is determined by

its variable name, not the object that it referencesits variable name, not the object that it references

8-9

Pitfall: No Late Binding for Static Pitfall: No Late Binding for Static MethodsMethods

There are other cases where a static There are other cases where a static method has a calling object in a more method has a calling object in a more inconspicuous wayinconspicuous way

For example, a static method can be For example, a static method can be invoked within the definition of a invoked within the definition of a nonstatic method, but without any explicit nonstatic method, but without any explicit class name or calling objectclass name or calling object

In this case, the calling object is the In this case, the calling object is the implicit implicit thisthis

8-10

The The finalfinal Modifier Modifier A A methodmethod marked marked finalfinal indicates that it indicates that it

cannot be overridden with a new cannot be overridden with a new definition in a derived classdefinition in a derived class If If finalfinal, the compiler can use early binding , the compiler can use early binding

with the methodwith the method

public final void someMethod() { . . . }public final void someMethod() { . . . }

A A classclass marked marked finalfinal indicates that it indicates that it cannot be used as a base class from which cannot be used as a base class from which to derive any other classesto derive any other classes

8-11

Upcasting and Upcasting and DowncastingDowncasting

UpcastingUpcasting is when an object of a derived class is is when an object of a derived class is assigned assigned toto a variable of a base class (or any ancestor a variable of a base class (or any ancestor class)class)

Vehicle v1 = new Vehicle(); //Base class objectVehicle v1 = new Vehicle(); //Base class object

Bus b1 = new Bus(2, 55000, 37); //Derived class objectBus b1 = new Bus(2, 55000, 37); //Derived class object

v1 = b1;v1 = b1; DowncastingDowncasting is when a is when a type casttype cast is performed from a base class to is performed from a base class to

a derived class (or from any ancestor class to any descendent class)a derived class (or from any ancestor class to any descendent class) Downcasting has to be done very carefullyDowncasting has to be done very carefully In many cases it doesn't make sense, or is illegal:In many cases it doesn't make sense, or is illegal:

B1 = v1; B1 = v1; //will produce compiler error//will produce compiler errorB1 = (Bus)v1; B1 = (Bus)v1; //will produce run-time error//will produce run-time error

There are times, however, when downcasting is necessary, e.g., inside the There are times, however, when downcasting is necessary, e.g., inside the equalsequals method for a classmethod for a class

See Polymorphism3.javaSee Polymorphism3.javaRevisit Object3.javaRevisit Object3.java

8-12

Pitfall: DowncastingPitfall: Downcasting

It is the responsibility of the It is the responsibility of the programmer to use downcasting programmer to use downcasting only in situations where it makes only in situations where it makes sensesense The compiler does not check to see if The compiler does not check to see if

downcasting is a reasonable thing to dodowncasting is a reasonable thing to do Using downcasting in a situation Using downcasting in a situation

that does not make sense usually that does not make sense usually results in a run-time errorresults in a run-time error

8-13

Tip: Checking to See if Tip: Checking to See if Downcasting is LegitimateDowncasting is Legitimate

Downcasting to a specific type is only Downcasting to a specific type is only sensible if the object being cast is an sensible if the object being cast is an instance of that typeinstance of that type This is exactly what the This is exactly what the instanceofinstanceof operator operator

tests for:tests for:objectobject instanceof instanceof ClassNameClassName

It will return true if It will return true if objectobject is of type is of type ClassNameClassName; in particular, it will return true if ; in particular, it will return true if objectobject is an instance of any descendent class is an instance of any descendent class of of ClassNameClassName

8-14

Pitfall: Limitations of Copy Pitfall: Limitations of Copy ConstructorsConstructors

A copy constructor is supposed to create a A copy constructor is supposed to create a good copy of a new object from an good copy of a new object from an existing oneexisting one

However, when polymorphism is used, a However, when polymorphism is used, a copy constructor may have a strong copy constructor may have a strong limitationlimitation

See Polymorphism4.javaSee Polymorphism4.java

8-15

A First Look at the A First Look at the cloneclone MethodMethod

Every object inherits a method named Every object inherits a method named cloneclone from the from the Object Object classclass The method The method cloneclone has no parameters has no parameters It is supposed to return a It is supposed to return a deep copy deep copy of the of the

calling objectcalling object However, the inherited version of the However, the inherited version of the

method is not designed to be used as ismethod is not designed to be used as is Instead, each class is expected to override it Instead, each class is expected to override it

with a more appropriate versionwith a more appropriate version

8-16

A First Look at the A First Look at the cloneclone MethodMethod

The heading for the The heading for the cloneclone method defined in the method defined in the ObjectObject class is as follows: class is as follows:protected Object clone()protected Object clone()

The heading for a The heading for a cloneclone method that overrides method that overrides the the cloneclone method in the method in the ObjectObject class can differ class can differ somewhat from the heading abovesomewhat from the heading above A change to a more permissive access, such as from A change to a more permissive access, such as from

protectedprotected to to publicpublic, is always allowed when overriding , is always allowed when overriding a method definitiona method definition

Changing the return type from Changing the return type from ObjectObject to the type of the to the type of the class being cloned is allowed because every class is a class being cloned is allowed because every class is a descendent class of the class descendent class of the class ObjectObject

This is an example of a This is an example of a covariantcovariant return type return type

8-17

A First Look at the A First Look at the cloneclone MethodMethod

If a class has a copy constructor, the If a class has a copy constructor, the cloneclone method for that class can use the method for that class can use the copy copy constructorconstructor to create the copy returned by to create the copy returned by the the cloneclone method method

public Vehicle clone()public Vehicle clone(){{ return new Sale(this);return new Sale(this);}} and another example:and another example:

public Bus clone()public Bus clone(){{ return new Bus(this);return new Bus(this);}}

See Polymorphism5.javaSee Polymorphism5.java8-18

Pitfall: Limitations of Copy Pitfall: Limitations of Copy ConstructorsConstructors

Although the clone() methods may in fact use the copy Although the clone() methods may in fact use the copy constructors to perform the copying, this works because constructors to perform the copying, this works because the method the method cloneclone has the same name in all classes, and has the same name in all classes, and polymorphism works with method namespolymorphism works with method names

The copy constructors (i.e The copy constructors (i.e VehicleVehicle, , BusBus, , RaceCarRaceCar) have ) have different names, and polymorphism doesn't work with different names, and polymorphism doesn't work with methods of different namesmethods of different names

8-19

Pitfall: Sometime the Pitfall: Sometime the cloneclone Method Return Type is Method Return Type is ObjectObject

Prior to version 5.0, Java did not allow covariant return types, Prior to version 5.0, Java did not allow covariant return types, so no changes whatsoever were allowed in the return type of so no changes whatsoever were allowed in the return type of an overridden methodan overridden method

Therefore, the Therefore, the cloneclone method for all classes had method for all classes had ObjectObject as its as its return typereturn type

Consequently, the Consequently, the cloneclone method for any class, i.e. the method for any class, i.e. the Vehicle Vehicle class would have looked like this:class would have looked like this:public Object clone()public Object clone(){{ return new Vehicle(this);return new Vehicle(this);}}

Therefore, the result needed to always be type casted when Therefore, the result needed to always be type casted when using a using a cloneclone method written for an older version of Java method written for an older version of JavaVehicle newVec = (Vehicle)originalVec.clone();Vehicle newVec = (Vehicle)originalVec.clone();

8-20

Pitfall: Sometime the Pitfall: Sometime the cloneclone Method Return Type is Method Return Type is ObjectObject

It is still perfectly legal to use It is still perfectly legal to use ObjectObject as the as the return type for a clone method, even with return type for a clone method, even with classes defined after Java version 5.0classes defined after Java version 5.0 When in doubt, it causes no harm to include When in doubt, it causes no harm to include

the type castthe type cast

For example, the following is legal for the For example, the following is legal for the clone method of the Vehicle class:clone method of the Vehicle class:Vehicle newVec = originalVec.clone();Vehicle newVec = originalVec.clone();

However, adding the following type cast However, adding the following type cast produces no problems:produces no problems:Vehicle newVec = (Vehicle)originalVec.clone();Vehicle newVec = (Vehicle)originalVec.clone();

8-21

Abstract ClassAbstract Class Sometimes, it is does NOT make sense to create Sometimes, it is does NOT make sense to create

objects from specific classes objects from specific classes

In such case, these classes should be created as In such case, these classes should be created as abstractabstract

An abstract class can only be used to derive other An abstract class can only be used to derive other classes; you cannot create objects from an abstract classes; you cannot create objects from an abstract classclass

An abstract class must have at least one An abstract class must have at least one abstract abstract methodmethod

8-22

Abstract MethodAbstract Method An abstract method has a complete An abstract method has a complete

method heading, to which has been added method heading, to which has been added the modifier the modifier abstractabstract

It has no method body, and ends with a It has no method body, and ends with a semicolon in place of its bodysemicolon in place of its body

public abstract long getSerNumber();public abstract long getSerNumber();

An abstract method cannot be privateAn abstract method cannot be private

See Abstract1.javaSee Abstract1.java

8-23

Abstract ClassAbstract Class

An abstract class can have any number An abstract class can have any number of abstract and/or fully defined methodsof abstract and/or fully defined methods

If a derived class of an abstract class If a derived class of an abstract class adds to or does not define all of the adds to or does not define all of the abstract methods, then it is abstract abstract methods, then it is abstract also, and must add also, and must add abstractabstract to its to its modifiermodifier

A class that has no abstract methods A class that has no abstract methods is called a is called a concrete classconcrete class

8-24

Pitfall: You Cannot Create Pitfall: You Cannot Create Instances of an Abstract ClassInstances of an Abstract Class

An abstract class constructor cannot be An abstract class constructor cannot be used to create an object of the abstract used to create an object of the abstract classclass However, a derived class constructor will However, a derived class constructor will

include an invocation of the abstract class include an invocation of the abstract class constructor in the form of constructor in the form of supersuper

Although an object of an abstract class Although an object of an abstract class cannot be created, it is perfectly fine to cannot be created, it is perfectly fine to have a parameter of an abstract class typehave a parameter of an abstract class type This makes it possible to plug in an object of This makes it possible to plug in an object of

any of its descendent classesany of its descendent classes

8-25