简体   繁体   English

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

[英]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.

相关问题 为什么外部 Java 类可以访问内部类私有成员? - Why can outer Java classes access inner class private members? 从Java的封闭类继承的内部类 - Inner classes inherited from the enclosing class in Java 内部类甚至可以访问外部类的私有成员。这是否侵犯了隐私? - Inner classes can access even the private members of the outer class.. doesn't it violates the privacy? 在更高版本的 Java 中,内部类如何访问封闭类的私有成员? - How do inner class access enclosing class' private members in higher versions of Java? 封闭类型的静态嵌套子类仍然可以引用私有字段成员,为什么? - Static nested sub-classes of the enclosing type can still refer to the private field members, why? 为什么嵌套的子类可以访问其父类的私有成员,但是子孙却不能呢? - Why can nested child classes access private members of their parent class, but grandchildren cannot? 公共嵌套类的子类无法访问封闭类的私有成员 - Subclass of a public nested class is unable to access private members of enclosing class 类似于“限定此条件”之类的东西,但是用于访问嵌套类的成员而不是封闭类 - Something like “qualified this” but for accessing members of nested classes instead of the enclosing class Java中的内部类和封闭实例? - Inner Classes and Enclosing Instances in java? 内部类的继承和对封闭类方法/字段的访问 - Inner classes inheritance and access to enclosing class methods/fields
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM