I have a quite simple question regarding the following code snippet.
public class SuperClass {
public SuperClass() {
this.test(); //Always invokes the overridden method in the sub-class.
}
public void test() {
System.out.println("test() in SuperClass.");
}
}
public final class SubClass extends SuperClass {
public SubClass() {
super();
}
@Override
public void test() {
System.out.println("test() in SubClass.");
}
}
public final class Test {
public static void main(String... args) {
SubClass subClass=new SubClass();
}
}
In this example, the only line in the main()
method indirectly passes a call to the super class constructor in which it attempts to invoke the test()
method as this.test()
.
The method invoked by this.test()
in the super class constructor is however, the overridden method in SubClass
.
Why doesn't the method call this.test()
in the super class constructor invoke its own method in the super class itself (though this
refers to the current instance by which this method is to be invoked)?