在Java嵌套类中,封闭类是否可以访问内部类的私有成员? [英] In Java nested classes, can the enclosing class access private members of inner classes?

查看:203
本文介绍了在Java嵌套类中,封闭类是否可以访问内部类的私有成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,内部类可以访问封闭类的私有成员。但是外部类可以访问内部类的私有成员吗?这与内部阶级是否是静态无关。我认为这不是真的,但下面的代码似乎编译并正常工作。

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


推荐答案

是, 没关系。从JLS,第6.6节。 1

Yes, that's fine. From the JLS, section 6.6.1:


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

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.

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

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.

这篇关于在Java嵌套类中,封闭类是否可以访问内部类的私有成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆