在 Java 嵌套类中,封闭类可以访问内部类的私有成员吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2221607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 20:08:14  来源:igfitidea点击:

In Java nested classes, can the enclosing class access private members of inner classes?

javainner-classes

提问by user236215

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.

在 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;
    }
}

回答by Jon Skeet

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.

在字节码层面,我相信这都是通过添加合成包访问方法来实现的。