Java Enum access to private instance variable

后端 未结 6 1833
名媛妹妹
名媛妹妹 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:40

    You can't do

    SomeEnum.VALUE1 = "Value4";
    System.out.println(SomeEnum.VALUE1);
    

    but you can do

    SomeEnum.VALUE1.value = "Value4";
    System.out.println(SomeEnum.VALUE1);
    

    and value really changes, but not the static final VALUE1.

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

    You can access a private field in an outer/inner class, but I cannot find an example of where you can access it from another class (in the same package for example).

提交回复
热议问题