相关疑难解决方法(0)

为什么外部Java类可以访问内部类私有成员?

我观察到外类可以访问内部类私有实例变量.这怎么可能?以下是演示相同内容的示例代码:

class ABC{
    class XYZ{
        private int x=10;
    }

    public static void main(String... args){
        ABC.XYZ xx = new ABC().new XYZ();
        System.out.println("Hello :: "+xx.x); ///Why is this allowed??
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么允许这种行为?

java private class inner-classes private-members

169
推荐指数
6
解决办法
9万
查看次数

为什么枚举类型上的私有字段对包含类可见?

public class Parent {

    public enum ChildType {

        FIRST_CHILD("I am the first."),
        SECOND_CHILD("I am the second.");

        private String myChildStatement;

        ChildType(String myChildStatement) {
            this.myChildStatement = myChildStatement;
        }

        public String getMyChildStatement() {
            return this.myChildStatement;
        }
    }

    public static void main(String[] args) {

        // Why does this work?
        System.out.println(Parent.ChildType.FIRST_CHILD.myChildStatement);
    }
}
Run Code Online (Sandbox Code Playgroud)

在参考这个枚举时,是否有关于Parent子类,同一包中的类等的访问控制的附加规则?我在哪里可以找到规范中的规则?

java enums access-control

10
推荐指数
2
解决办法
6464
查看次数