COMP2247 - Algorithms and Data Structures

Syllabus Software Installation Assignments Tests
Lectures and Labs
**Back to Full Menu**

OOP - Polymorphism Pet Program Payroll Program Class Roster Program



Polymorphism


In this section, we study Polymorphism.

Polymorphism

Rather than "programming in specific", polymorphism enables us to “programming in general”.

With polymorphism, it is possible to design and implement programs that can be extended by adding new classes with little or no modification to the generic portions of the programs.

Relationships among Objects in an Inheritance Hierarchy

An object of a subclass can be treated as an object of its superclass.

In other words, a reference variable of a superclass type can refer to an object of its subclass.

Let's use the Pet program as an example.

Pet p1, p2;
Dog d1, d2;
Cat c1, c2;

p1 = new Dog();    //It is legal to use superclass reference to refer to subclass object.
c1 = new Cat();
p1 = c1;    //It is legal to use superclass reference to refer to subclass object.

c2 = new Pet();    //It is illegal to use subclass reference to refer to superclass object.

c2 = (Cat) p1;   //legal, but dangerous

if( p1 instanceof Cat) {
     c2 = (Cat) p1;      //It is legal and safe.
}

The instanceof Operator

Use the instanceof operator to determine whether an object is an instance of a particular class.

Polymorphism and Dynamic Binding

Let's say the subclass has overridden a method in the superclass. The program uses the superclass reference to refer to the subclass object. If the method is called with this superclass reference, the subclass’s version of the method is actually executed.

Basically, Java performs dynamic binding or late binding when a variable contains a polymorphic reference.

The Java Virtual Machine determines at run-time which method to call, depending on the type of object that the variable refers to.

It is the object’s type, rather than the reference type, that determines which method is called.

Advantage of Polymorphism

The real power of polymorphism is that it allows a single variable to refer to objects from different subclasses in the same inheritance hierarchy.

A program can create an array or ArrayList of superclass references that can refer to objects of many subclass types.

During the program execution, it uses the superclass references to invoke the polymorphic method and the actual subclass' version will be called.