所以,一个朋友给我发来了这段代码,并说它已经成功编译并返回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的源代码,这种情况就不会发生,并且您将无法编译。
发布于 2014-04-17 17:38:29
private的要点是“外部”类不应该能够看到私有变量。但是A和B都是同一个类的一部分,或者彼此嵌套在一起,所以它们可以访问彼此的私有成员。
所以这将会起作用:
public class A {
private void a() {
int bVal = this.new B().val; //! Accessing B private
}
class B {
A a = new A();
private int val = 10;
public void b() {
a.a(); // !! Accessing A private
}
}但是,即使A和B都在相同的文件中,但不在彼此内部,这也会失败:
class A {
private void a() {}
}
class B extends A {
A a = new A();
public void b() {
a.a(); // can't see even if B extends A
}
}发布于 2014-04-17 18:41:48
这是因为A类和B类都嵌套在另一个类中,也就是说,这两个类都是另一个相同类的内部类(或“部分”)。因为它们(数据成员和方法)基本上是外部类的成员,所以即使是私有的,它们也可以在其他内部类中访问。
Java允许我们嵌套类,如果您不了解嵌套类,请先阅读以下内容:
http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
class Outer{
class A {
private int f() {
return 42;
}//Method f() is a private member of A and accessible by Outer
}
class B extends A {
public int f2() {
return super.f();
}//As class B is inner class of Outer it can access members of outer,thus indirectly member of A
}
public static void main(String[] args) {
System.out.print(new B().f2());
}
}https://stackoverflow.com/questions/23128728
复制相似问题