Java – why are private fields on enumeration types visible to containing classes?
•
Java
public class Parent {
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 other rules for access control of parent and child classes participating in this enumeration, classes in the same package, etc? Can I find these rules in the specification?
Solution
It has nothing to do with enumeration - it has to do with private access from containing types to nested types
From Java language specification, section 6.6 1:
For example, this is also valid:
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; } }
Interestingly, C # works a little differently - in C #, private members can only be accessed in the program text of types, including any nested types So the above java code will not work, but doing so will:
// 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); } } }
... but if you just put console Change writeline to system out. Println, then it will be compiled in Java So Java is basically more relaxed than c#'s private members
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码