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
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.