所以,一个朋友给我发来了这段代码,并说它已经成功编译并返回42。但是,麻烦的是父类中的方法“return”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());
}它返回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。
发布于 2014-04-17 16:59:39
因为这两个类(A和B)都嵌套在Main中,所以它们可以访问private int f()方法。
如果您在顶级类中提取A和B的源代码,这种情况就不会发生,并且您将无法编译。
https://stackoverflow.com/questions/23128728
复制相似问题