Is it OK/possible to modify instance variables inside an enum declaration?

余生颓废 提交于 2020-01-06 12:42:42

问题


Or, to re-phrase it: can enum types be "mutable"?

public enum Foo {
    ONE,TWO;

    private String bar;

    Foo() { this.bar = ""; }
    String bar() { return bar; }

    // legal?
    void bar(String bar) { this.bar = bar; }
}

I guess if I want to modify it, it's no longer an enum type.

Thoughts?


回答1:


It's absolutely valid. It's just a really bad idea. Callers are likely to expect the enum to be properly immutable. In some cases you might want to make it "appear" to be immutable, e.g. with caching, while still mutating the internal variables... but that's very much an edge case.

As to why Java lets you do this... even if it forced all member variables to be final, that wouldn't make enum values truly immutable... for example, you could have a List<String> which was modified each time you called a particular method...

Fundamentally, Java's not very good at enforcing immutability.



来源:https://stackoverflow.com/questions/5082227/is-it-ok-possible-to-modify-instance-variables-inside-an-enum-declaration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!