Lets say that we have the following code:
class A {
public void doLogic() {
System.out.println("doLogic from A");
}
}
class B extends A {
@Override
public void doLogic() {
System.out.println("doLogic from B");
}
public void doDifferentLogic() {
System.out.println("doDifferentLogic from B");
super.doLogic();
}
}
class C extends B {
@Override
public void doLogic() {
System.out.println("doLogic from C");
}
}
public class Test {
public static void main(String[] args) {
C c = new C();
c.doDifferentLogic();
}
}
When we execute this code the expected behavior is the following:
Since c holds a reference to object of class C, when you invoke the c.doDifferentLogic()
method the JVM searches for the method in the C class and since it is not found it starts looking at the inheritance tree. As expected the doDifferentLogic()
method is found in the super class and executed. However the construct super.doLogic()
is expected to look from the current reference "Point of View", which is of type C. So the super of C should B, but instead the method from the top class A is invoked.
If you remove the super
keyword, or replace it with the this
keyword (which is the same as "this" is implicit), you get the expected polymorphic behavior and the doLogic()
from C class is invoked.
So my question is:
Should call to super.doLogic()
be this.super.doLogic()
(2), instead of static.super.doLogic()
(1) ?
Both are invalid constructs, they are here just to try to explain myself better.
(1)or in other words - from the reference to the current object c , get the superclass of the current object and invoke the doLogic()
method instead of
(2)from this class get the superclass and invoke its doLogic()
method ?