Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at run-time rather than compile-time.
In this process, an overridden method is called through the reference variable of a super-class. The determination of the method to be called is based on the object being referred to by the reference variable.
************************* Example of Runtime Polymorphism *****************************
In this example, we are creating two classes Bike and Passion. Passion class extends Bike class and overrides its run() method. We are calling the run method by the reference variable of Parent class. Since it refers to the subclass object and subclass method overrides the Parent class method, subclass method is invoked at run-time.
Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.
class Bike{
void run(){System.out.println("running");}
}
class Passion extends Bike{
void run(){System.out.println("running safely with 60km");}
public static void main(String args[]){
Bike b = new Passion();//upcasting
b.run();
}
}
================================ Output ==================================
running safely with 60km.
------------------------------------------------------------------------------------------------------------------
************************** Runtime Polymorphism with data member ************************
Method is overridden not the data members, so runtime polymorphism can´t be achieved by data members.
In the example given below, both the classes have a data-member speedlimit, we are accessing the data-member by the reference variable of Parent class which refers to the subclass object. Since we are accessing the data-member which is not overridden, hence it will access the data-member of Parent class always.
------------------------------------------------------------------------------------------------------------------
Rule: Runtime polymorphism can´t be achieved by data members.
------------------------------------------------------------------------------------------------------------------
class Bike{
int speedlimit=90;
}
class Honda extends Bike{
int speedlimit=150;
public static void main(String args[]){
Bike obj=new Honda();
System.out.println(obj.speedlimit);//90
}
}
================================ Output =================================
90
4