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?

3
  • 1
    See stackoverflow.com/questions/1801718/… Commented Mar 9, 2013 at 16:03
  • 1
    By convention, enums are always uppercase! Commented Mar 9, 2013 at 16:04
  • 1
    private means visible to the class only, but this is exactly what you have. Commented Mar 9, 2013 at 16:06

5 Answers 5

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,

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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?

Comments

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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.