C1.bar()被执行了,不应该是C2.bar吗?

C1.bar() is executed, shouldn't it be C2.bar?

我已经设置了这两个 classes,作为学习 this() 和 super() 的区别和用途的示例,但是,输出并不像预期的那样

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();
    }
}

据我所知,调用C2.foo()应该是到C2中定义的foo方法,后面那句super.foo(),应该是调用C1.foo() ,打印"C1.foo()"并调用C2.foo(),因为调用super的class是C2,然而,输出是:

C1.foo()
C1.bar()

为什么代码会这样?为什么 this.bar();调用 C1 中定义的 bar 方法?

方法 bar() 是私有的。它不能被覆盖。 C2.bar 仅在 C2 中可见,并且只能在 C2 中直接调用。将 bar() 的可见性更改为 protected 或 public 在 bothC1C2 any 你会看到区别.

C2.bar() 方法不会覆盖 C1.bar() 方法,因为 C1.bar() 方法是私有的。但是,C1.foo() 方法正在调用这个确切的方法 C1.bar()。所以你得到输出:

C1.foo()
C1.bar()

没有其他人在调用 "stand alone" 方法 C2.bar()。但是,当您将 C1.bar() 更改为 protectedpublic 时,这一切都会改变。当覆盖是有意的时,您可以使用 @Override 注释来明确您的意图。当你不覆盖你想覆盖的方法时,它会抱怨。

 protected void foo() {
    System.out.println("C1.foo()");
    this.bar();
   }

因为 this.bar() 被 C1 的函数 foo() 调用 class 所以 C1 class 的 bar() 函数被调用。