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

发布于 2024-08-20 19:46:34 字数 356 浏览 3 评论 0原文

在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不交电费瞎发啥光 2024-08-27 19:46:34

是的,没关系。来自 JLS,第 6.6 节。 1:

否则,如果成员或构造函数被声明为 private,则当且仅当访问发生在包含成员声明的顶级类 (§7.6) 的主体内时,才允许访问或构造函数。

您甚至可以在另一个嵌套类型 Y 中引用嵌套类型 X 的私有成员,只要它们共享顶级类即可。

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

Yes, that's fine. From the JLS, section 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.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文