public class XXX {
@Test
public void test() {
B b = new B();
b.doY();
}
}
class A {
public void doY() {
XProcedure.doX(this);
}
}
class B extends A {
public void doY() {
super.doY();
XProcedure.doX(this);
}
}
class XProcedure {
public static void doX(A a) {
System.out.println("AAAA!");
}
public static void doX(B b) {
System.out.println("BBBB!");
}
}
The output is
AAAA!
BBBB!
And I wonder why?
Although XProcedure has two methods with the same name – doX, the two signatures are different. The first method gets an instance of class A as a parameter, and the second one gets an instance of class B.
When you call
XProcedure.doX(this), the correct method is called according to the class of the passed parameter.“AAAA!” is printed because of the
super.doY()call.“BBBB!” is printed because of the
XProcedure.doX(this);call.thisdiffers in A’s constructor fromthisin B’s constructor for the reasons in Che’s answer. Although A’s contructor is called from within a B’s constructor, in A’s scope, the instance is of class A.