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:
例如,这也是有效的: 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#的私人成员更松懈. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
