Java12: Polymorphism

An ability of an object to take many forms. Any object that has an inheritance relationship is said to be polymorphic. This is usually used when a parent class reference is used to refer to a child class object.

In Java, all object is polymorphic because all object is a subtype of the Object class, so all objects have an IS-A relationship with the Object class. All objects also have an IS-A relationship with their own type.

class Shape{
    // codes...
}
class Rectangle extends Shape{
    // codes...
}
Rectangle rect  = new Rectangle()
Shape shape = rect;
Object obj = rect;

All these statements are correct.

  • Rectangle is-a Rectangle
  • Rectangle is-a Shape
  • Rectangle is-a Object

When using parent class reference to refer to child class objects, it is known as upcasting. For example when we use the Shape class reference called shape to refer to the Rectangle class object called rect, where the rect is said to be upcasted or promoted to become Shape type.

Polymorphism can be realized by method overloading and method overriding. Method overloading is compile-time polymorphism. Method overriding is runtime polymorphism. When upcasting takes place, what we are actually witnessing is runtime polymorphism.

The following example consists of Vehicle (the parent class) and two child classes Car and Bike. Both child classes override the stop() method of the parent class.

class Vehicle{
    void stop(){
        System.out.println("Apply break");
    }
}
class Car extends Vehicle{
    void stop(){
        System.out.println("Step on break pedal");
    }
}
class Bike extends Vehicle{
    void stop(){
        System.out.println("Press break lever");
    }
}
class Demo{
    public static void main(String[] args){
        Vehicle v1 = new Car();
        Vehicle v2 = new Bike();

        v1.stop();
        v2.stop();
    }
}

Output

Step on break pedal
Press break lever

Though Vehicle has its own stop() method, it was never called for execution. Instead, the stop() method of its corresponding child object is called. This is polymorphism.

Polymorphism makes coding consistent. Promotes code reuse, where an already tested and implemented code can be used in a new project. The same reference variable can be used to refer to multiple subtypes. Debugging a code becomes easier.

A post by Cuber

Comments

Popular posts from this blog

Drawing Simple Pie Chart

VB.net connecting to SQL Server

VB.net