I have both these classes set up, as an example for learning the differences and uses of this() and super() however, the output is not as expected
class C1 {
protected void foo() {
System.out.println("C1.foo()");
this.bar();
}
private void bar() {
System.out.println("C1.bar()");
}
}
class C2 extends C1 {
public void foo() {
super.foo();
}
public void bar() {
System.out.println("C2.bar");
}
public static void main(String[] args) {
new C2().foo();
}
}
From what I know, calling C2.foo() should go to the method foo defined in C2, after that the sentence super.foo(), should be calling C1.foo(), printing "C1.foo()" and calling C2.foo(), because the class calling the super was C2, however, the output is:
C1.foo()
C1.bar()
why does the code behave like that? And why is the this.bar(); calling the bar method defined in C1?
The C2.bar()
method does not override the C1.bar()
method because the C1.bar()
method is private. However, the C1.foo()
method is calling this exact method C1.bar()
. So you get the output:
C1.foo()
C1.bar()
Noone else is calling the "stand alone" method C2.bar()
. However, this all changes when you change C1.bar()
to be protected
or public
. When the override was intended you can use the @Override
annotation to make your intention clear. It will complain when you don't override a method you wanted to override.