Java Enum access to private instance variable

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

Consider the example:

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

    private SomeEnu         


        
6条回答
  •  耶瑟儿~
    2021-02-05 11:25

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

    The Enum instances have these traits. But no one said, these instances are immutable like Integer or String. So you can modify the values.

    That does not mean that this is recommended practice! It isn't.

    Edit

    To explain a little more:

    "Enum implicitly static" means:

    enum Foo { FOO };
    

    Here FOO is static, although the normal Java syntax would suggest, that FOO is an instance variable wrongly named like a constant. You also access it like a static variable.

    "Enum implicitly final" means:

    enum Foo { FOO, BAR };
    Foo.FOO = Foo.BAR;
    

    is not allowed. The reference stored in FOO cannot be changed. You also cannot create new instances.

    "Enum not implicitly immutable" means: Foo.FOO will give you an object. A standard object. If the object allows modifications of its own content - so it be. This is not forbidden.

提交回复
热议问题