1

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?

dh4ze
  • 449
  • 1
  • 5
  • 10
  • Because, as i know, this refers to the class that got the message, so, C2 was the one that got new C2().foo(), after that, it called super.foo(), but the class that this is refering to shouldn't change, after tyhat, when this is called inside C1, it should refer to C2. – Martin Araya Aug 24 '19 at 22:57

3 Answers3

1

The method bar() is private. It cannot be overridden. C2.bar is only visible from C2 and can only be called from C2 directly. Change visibility of bar() to protected or public in both classes C1 and C2 any you will see the difference.

mentallurg
  • 4,967
  • 5
  • 28
  • 36
1

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.

Progman
  • 16,827
  • 6
  • 33
  • 48
  • i think i understand that, but i have another piece of code that does something similar yet different, and both outputs are "contradictory", should i edit this question with the other piece of code added, or should i delete this one and post another with both? (first time posting in stackoverflow) – Martin Araya Aug 24 '19 at 23:03
  • @MartinAraya Maybe you can/should try to work it out first with the new information you have. Keep in mind that Stack Overflow is not a forum. Please take the [tour] to learn how Stack Overflow works. – Progman Aug 24 '19 at 23:08
0
 protected void foo() {
    System.out.println("C1.foo()");
    this.bar();
   }

Its because this.bar() is being called by the function foo() of the C1 class so bar() function of C1 class is being called.