Run time polymorphism: If the polymorphism exhibits at run time, then it is called run time polymorphism. Method overriding is an example of run time polymorphism. If we use the same method in subclass, then subclass method will override the super class method. To avoid that we can use run time polymorphism. So java virtual machine knows which method to call at run time.
Example:
class base
{
void show()
{
System.out.println("This is base class") ;
}
}
class sub extends base
{
void show()
{
System.out.println("This is sub class") ;
}
}
class runtimepoly
{
public static void main(String args[])
{
sub ob=new sub();
ob.show();
sub ob1=new sup();
ob1.show();
}
}
Output:
This is sub class
This is base class
In the above example, when we call ob.show(), it will call only sub class method. Because the sub class method will over ride the super class method. To avoid that we will invoke super class by creating an object, so now ob1 will call super class method.