Runtime Polymorphism

Polymorphism means "one interface multiple behaviour". Polymorphism allow programmer to write multiple method with same name. Method overloading is considered compile time polymorphism because which method to be executed is decided by compiler on compile time.

On the other side in run time polymorphism, decision about which method should be called is taken at run time.

Example :


class A 
{
void show(){System.out.println("A class");}
}
class B extends A
{
void show(){System.out.println("B class");}
}
class C extends B
{
void show(){System.out.println("C class");}
}
class demo
{
public static void main(String ...arg)
{
A ref=new B(); // reference variable of class A and object of class B
ref.show();
ref=new C();
ref.show();

}
}
/*Output:
B class
C class
*/


Reference variable of parent class ref holding reference of B class object. This ref variable will call show method of class B.

When ref will be having reference to C class object, then show method of C class will be called.



This concept also known as Dynamic method dispatch