6
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 1 is shown if it a private member in enum?

ericmoraess
  • 374
  • 1
  • 7
  • 16

5 Answers5

5

Outer classes have full access to the member variables of their inner classes, therefore i is visible in the Test class.

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

Reimeus
  • 158,255
  • 15
  • 216
  • 276
3

It's (i) a member field being referenced within the same class (MyEnum); no access modifier prevents that - the private access modifier defined on i will prevent it's visibility outside this class. Suggested Reading

Scorpion
  • 3,938
  • 24
  • 37
1

private access from a containing type to a nested type is permitted, see Why are private fields on an enum type visible to the containing class?

Community
  • 1
  • 1
hflzh
  • 634
  • 5
  • 12
0

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

Youans
  • 4,801
  • 1
  • 31
  • 57
0

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

AmitG
  • 10,365
  • 5
  • 31
  • 52