Demonstrate runtime polymorphism - Java

Q. Write a java program to demonstrate the runtime polymorphism.

Answer:

Runtime Polymorphism:
Runtime polymorphism existed at runtime rather at compile time. Java compiler does not decide which method is called at compile time. Only JVM decide to which method is called at runtime.

In this example, we are creating three classes and each class having the show () method. Base2 class extends Base1 and Base3 class extends the Base2. It is also known as method overriding.

Base1.java

class Base1
{
    Base1()
    {
        System.out.println("Constructor of Base1 ");
    }
    public void show()
    {
        System.out.println ("method of class Base1");
    }
}


Base2.java

class Base2 extends Base1
{
    Base2()
    {
         System.out.println("Constructor of Base2");
    }
    public void show()
    {
        System.out.println ("method of class Base2");
    }
}


Base3.java

class Base3 extends Base2
{
   Base3()
   {
        System.out.println("Constructor of Base3");
   }
   public void show()
   {
       System.out.println("method of class Base3");
   }
}


Derive.java

public class Derive
{
   public static void main (String args [])
   {
       Base1 obj1 = new Base1();
       Base1 obj2 = new Base2();
       Base2 obj3 = new Base3();
       obj1.show();
       obj2.show();
       obj3.show();
   }
}


Output:

runtime polymorphism