Consider the example:
enum SomeEnum {
VALUE1("value1"),
VALUE2("value2"),
VALUE3("value3")
;
private String value;
private SomeEnum(final String value) {
this.value = value;
}
//toString
public String toString() {
return value;
}
}
How come can we do this (and the value really changes)?
SomeEnum.VALUE1.value = "Value4";
System.out.println(SomeEnum.VALUE1);
Isn’t that enum instance(s) are implicitly static and final? Also, since value is private, why can I access it outside other classes?
No-one seems to have addressed the private aspect. My guess is that you’re accessing the private field from a containing type – that your enum is actually a nested type, like this:
That’s entirely legitimate and normal – you can always access private members of a nested type from the containing type.
If you make the enum a top-level type, you won’t see this.
As for changing values – as everyone else has said,
VALUE1is implicitly static and final, but that doesn’t stop you from changingVALUE1.value. Again, this is entirely in accordance with how Java works elsewhere – if you have a static field of typeList, you can still add entries to it, because that’s not modifying the field itself.If you want to make
SomeEnumproperly immutable, make thevaluefieldfinal.