1 java inheritance private public
所以,有一位朋友给我发了这个代码并说它已成功编译并返回42.但是,令人困扰的是父类中的方法"返回"42是私有的,并且被调用的方法是在子类中,它是公开的.那么,任何人都能说出为什么以及如何运作?
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());
}
Run Code Online (Sandbox Code Playgroud)
它返回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());
}
Run Code Online (Sandbox Code Playgroud)
它仍然返回42.
| 归档时间: |
|
| 查看次数: |
130 次 |
| 最近记录: |