为什么枚举类型上的私有字段对于包含类可见? [英] Why are private fields on an enum type visible to the containing class?
问题描述
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);
}
}
有关访问控制的其他规则父子类,同一个包中的类等,参考这个枚举?我在哪里可以在规范中找到这些规则?
Are there any additional rules with regard to access control for Parent subclasses, classes within the same package, etc., in reference to this enum? Where might I find those rules in the spec?
推荐答案
它与枚举无关 - 它有一切使用从包含类型到嵌套类型的私有访问。
It has nothing to do with it being an enum - it has everything to do with private access from a containing type to a nested type.
否则,如果成员或构造函数被声明为
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.
例如,这也是有效的:
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代码将无法正常工作,但是这将是:
Interestingly, C# works in a slightly different way - in C# a private member is only accessible within the program text of the type, including from any nested types. So the above Java code wouldn't work, but this would:
// 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#更松懈。
... but if you just change Console.WriteLine to System.out.println, this does compile in Java. So Java is basically a bit more lax with private members than C# is.
这篇关于为什么枚举类型上的私有字段对于包含类可见?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!