Example of Runtime polymorphism in Java?

Yes this is Runtime polymorphism in Java

In static polymorphism, compiler itself determines which method should call. Method overloading is an example of static polymorphism.

In runtime polymorphism, compiler cannot determine the method at compile time. Method overriding(as your example) is an example of runtime polymorphism. Because in Runtime polymorphism (as your example), the signature of methodA() is similar in both the class X(base class) and Y(child class). So compiler cannot determine method at compile time which should execute. Only after object creation(which is a run time process), the runtime environment understand the exact method to call.

It is because of that in this case, obj1.methodA() calls methodA() in Class X since obj1 is reference variable of object created for class X

AND obj2.methodA() calls methodA() in Class Y since obj2 is reference variable of object created for class Y


For your better understanding i've tried modulating your code. Note the call for constructor for both the classes.

class X
{
    X(){
        System.out.println("X constructor called");
    }
    public void methodA() //Base class method
    {
        System.out.println ("hello, I'm methodA of class X");
    }
}

class Y extends X
{
    Y(){
         System.out.println("Y constructor called");
    }

    public void methodA() //Derived Class method
    {
        System.out.println ("hello, I'm methodA of class Y");
    }
}

public class Z
{
   public static void main (String args []) {
       X obj1 = new X(); // Reference and object X
       X obj2 = new Y(); // X reference but Y object
       obj1.methodA();
       obj2.methodA();
   }
}

output :-

X constructor called

X constructor called

Y constructor called

hello, I'm methodA of class X

hello, I'm methodA of class Y

Carefully, look where objects have been created. It seems reference of X is being created using y. Method for X's is expected to be called but constructor call of Y for X reference creation says indirectly that memory has been allocated to Y's Object before X's reference is created. Take a look at the consoles for clarification.