Consider the example:
enum SomeEnum {
VALUE1(\"value1\"),
VALUE2(\"value2\"),
VALUE3(\"value3\")
;
private String value;
private SomeEnu
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:
class Test
{
static void Main() {
// Entirely valid
SomeEnum.VALUE1.value = "x";
}
enum SomeEnum {
VALUE1("value1");
private String value;
private SomeEnum(final String value) {
this.value = value;
}
}
}
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, VALUE1
is implicitly static and final, but that doesn't stop you from changing VALUE1.value
. Again, this is entirely in accordance with how Java works elsewhere - if you have a static field of type List
, you can still add entries to it, because that's not modifying the field itself.
If you want to make SomeEnum
properly immutable, make the value
field final
.