Java Enum access to private instance variable

后端 未结 6 1827
名媛妹妹
名媛妹妹 2021-02-05 10:50

Consider the example:

enum SomeEnum {
    VALUE1(\"value1\"),
    VALUE2(\"value2\"),
    VALUE3(\"value3\")
    ;
    private String value;

    private SomeEnu         


        
6条回答
  •  -上瘾入骨i
    2021-02-05 11:43

    Isn't that enum instance(s) are implicitly static and final?

    Nope. Members of enum-instances such as value in your example can be mutable.

    (The references to the instances (SomeEnum.VALUE1 etc in your example) are final and static though.

    Also, since value is private, why can I access it outside other classes?

    You can't. An enum is a "class" with an enumerable number of instances. That's all.

    VALUE1 is in this case a an instance of the "class" SomeEnum, thus SomeEnum.VALUE1.value is an ordinary field like any other.


    When you do

    System.out.println(SomeEnum.VALUE1);
    

    you invoke SomeEnum.VALUE1.toString which accesses the value field. You're not accessing the value-field immediately.

    // Not possible since field is private.
    System.out.println(SomeEnum.VALUE1.value);
    

提交回复
热议问题