所以,一个朋友送我这个代码,并表示,它已成功编译并返回42 但是,在困扰的事情是在父类中的方法“返回”42是私有的,被调用的方法在子类中,并且是公共的。那么,任何人都可以说出为什么以及如何运作?Java中,继承 - 在父母的私有字段是通过孩子的公共方法访问
static class A {
private int f() {
return 42;
}
}
static class B extends A {
public int f2() {
return super.f();
}
}
public static void main(String[] args) {
System.out.print(new B().f2());
}
它返回42
我试图摆脱静态的,
class A {
private int f() {
return 42;
}
}
class B extends A {
public int f2() {
return super.f();
}
}
public static void main(String[] args) {
Main m= new Main();
B b= m.new B();
System.out.print(b.f2());
}
仍然会返回42