Sitemap

Thursday, June 25, 2015

Java: Dynamic Polymorphism

Polymorphism in Java has two types:
1. Compile time polymorphism (static binding)
2. Runtime polymorphism (dynamic binding).

Method overloading is an example of static polymorphism, while method overriding is an example of dynamic polymorphism.

public class Vehicle {
    public void move() {
        System.out.println("Vehicles can move!");
    }
}

class MotorBike extends Vehicle{
    public void move(){
    System.out.println("MotorBike can move and accelerate too!");
    }
}

class Test{
    public static void main(String[] args) {
        Vehicle vh = new MotorBike();
        vh.move(); // prints MotorBike can move and accelerate too!
        vh = new Vehicle();
        vh.move(); // prints Vehicles can move!
    }
}

It should be noted that in the first call to move(), the reference type is Vehicle and the object being referenced is MotorBike. So, when a call to move() is made, Java waits until runtime to determine which object is actually being pointed to by the reference.  In this case, the object is of the class MotorBike. So, the move() method of MotorBike class will be called. In the second call to move(), the object is of the class Vehicle. So, the move() method of Vehicle will be called.

More Info: http://www.javatpoint.com/static-binding-and-dynamic-binding
Info on typecasting: http://www.c4learn.com/java/java-type-casting-inheritance/

No comments:

Post a Comment