Search code examples
javaooppolymorphismdynamic-dispatch

Java method access on runtime polymorphism


I have the following java code.

class A {

        public void method1() {
            System.out.println("A 1");
            method2();
        }

        public void method2() {
            System.out.println("A 2");
        }

    }

    class B extends A {
        @Override
        public void method2() {
            System.out.println("B 2");
        }
    }

    public class Tester {
        public static void main(String[] args) {
            A a = new B();
            a.method1();
        }
    }

It prints

    A 1
    B 2
  • What exactly happens at runtime when a.method1() is called?
  • How is the derived method getting called from the parent?
  • Is it looking at the object and the method name string and calling the method during runtime?
  • Is it calling this.method2() by default?

Solution

  • Since the method method1(...) was never overridden, B inherits A's method1() and it is called as if it were defined in B.

    Since method1() calls method2() the overridden method method2() defined in B is called, when the instance was created with the B constructor.

    If you create another instance, with the A constructor, you will not get the overridden method2(...) defined in B, but get the original method2(...) defined in A.