在Java嵌套类中,封闭类可以访问内部类的私有成员吗?
在Java中,内部类可以访问封闭类的私有成员。但是外部类可以访问内部类的私有成员吗?这与内部类是否静态无关。我认为这不是真的,但以下代码似乎可以编译并正常工作。
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;
}
}
In Java, the inner class can access private members of enclosing class. 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;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,没关系。来自 JLS,第 6.6 节。 1:
您甚至可以在另一个嵌套类型 Y 中引用嵌套类型 X 的私有成员,只要它们共享顶级类即可。
在字节码级别,我相信这都是通过添加合成包访问方法来实现的。
Yes, that's fine. From the JLS, section 6.6.1:
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.
At the bytecode level, I believe this is all implemented by adding synthetic package-access methods.