为什么枚举类型上的私有字段对包含类可见? [英] 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屋!