Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private members in Enum Java [duplicate]

Tags:

java

enums

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?

like image 323
ericmoraess Avatar asked Mar 09 '13 15:03

ericmoraess


1 Answers

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,

like image 81
Reimeus Avatar answered Sep 19 '22 10:09

Reimeus