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

前端之家收集整理的这篇文章主要介绍了java – 为什么枚举类型上的私有字段对包含类可见?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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);
    }
}

有关参与此枚举的父子类,相同包中的类等的访问控制有其他规则吗?我可以在规范中找到这些规则吗?

解决方法

它与枚举无关 – 它与从包含类型到嵌套类型的私有访问有关.

Java language specification,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.

例如,这也是有效的:

public class Test {

    public static void main(String[] args) {
        Nested nested = new Nested();
        System.out.println(nested.x);
    }

    private static class Nested {
        private int x;
    }
}

有趣的是,C#的工作方式略有不同 – 在C#中,私有成员只能在类型的程序文本中访问,包括任何嵌套类型.所以上面的Java代码将不起作用,但是这样做会:

// C#,not Java!
public class Test
{
    private int x;

    public class Nested
    {
        public Nested(Test t)
        {
            // Access to outer private variable from nested type
            Console.WriteLine(t.x); 
        }
    }
}

…但是如果您只是将Console.WriteLine更改为System.out.println,那么它将以Java编译.所以Java基本上比C#的私人成员更松懈.

原文链接:https://www.f2er.com/java/122183.html

猜你在找的Java相关文章