[英]In Java nested classes, can the enclosing class access private members of inner classes?
In Java, the inner class can access private members of enclosing class.在 Java 中,内部类可以访问封闭类的私有成员。 But can the outer class access private members of inner class?但是外部类可以访问内部类的私有成员吗? This is irrespective of whether inner class is static or not.这与内部类是否是静态的无关。 I thought this is not true but the following code seems to compile and work fine.我认为这不是真的,但以下代码似乎可以编译并正常工作。
public class Outer {
class Inner {
private int i = 0;
private Inner() {}
}
public static void main(String[] args) {
Outer o = new Outer();
Outer.Inner oi = o.new Inner();
oi.i = 10;
}
}
Yes, that's fine.是的,没关系。 From the JLS, section 6.6.1 :从 JLS, 第 6.6.1 节:
Otherwise, if the member or constructor is declared
private
, then access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.否则,如果成员或构造函数被声明为private
,则当且仅当它出现在包含成员或构造函数声明的顶级类(第 7.6 节)的主体内时,才允许访问。
You can even refer to a private member of nested type X within another nested type Y so long as they share a top-level class.你甚至可以在另一个嵌套类型 Y 中引用嵌套类型 X 的私有成员,只要它们共享一个顶级类。
At the bytecode level, I believe this is all implemented by adding synthetic package-access methods.在字节码级别,我相信这都是通过添加合成包访问方法来实现的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.