Private members in Enum Java

public class Test { public static enum MyEnum { valueA(1),valueb(2),valuec(3),valued(4); private int i; private Object o; private MyEnum(int number) { i = number; } public void set(Object o) { this.o = o; } public Object get() { return o; } } public static void main(String[] args) { System.out.println(MyEnum.valueA.i); // private } } 

output: 1

Why is 1 displayed if it is a private member in an enumeration?

+4
source share
5 answers

Outer classes have full access to member variables of their inner classes, so i mapped to the Test class.

In contrast, if MyEnum was external to the Test class, the compiler will complain about the visibility of i ,

+4
source

This is (i) a member field referenced within the same class (MyEnum); access modifier does not prevent this - private access modifier defined on i will prevent its visibility outside this class. Recommended Reading

+3
source

private access from the containing type to the nested type is allowed, see Why are private fields of the enumeration type visible to the containing class?

+1
source

vlaueA is considered a static variable, so you can call it in MyEnum , since i in the same enum whice play the same as the class, so MyEnum can access valueA , which can access i

0
source

The outer class will have access to the inner member of the class, even if it is private, because you defined the main method inside the outer class.

0
source

All Articles