Why Java don't force to use final with enum properties

我们两清 提交于 2021-01-29 02:31:38

问题


Let's take a look with my enum definition here:

public enum Day {
    MONDAY(1),
    TUESDAY(2),
    WEDNESDAY(3);

    int index;

    Day(int i) {
        index = i;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    public static void main(String[] args) {
        Day x = MONDAY;
        Day y = MONDAY;
        x.setIndex(2);
        System.out.println(y.index);  // Ouput: 2
    }

In general, I know we should not implement code like that. To prevent this, why java don't use final for final int index like Java treat with interface's properties. Does anyone can explain that?


回答1:


Questions like "Why Java doesn't force to use of final for enum properties" have only one correct answer:

Because the Java designers did not design it that way.

We can only speculate as to why they didn't design it that way. The only people who really know the actual reasons are the designers themselves. And the chances are that even they wouldn't be able to remember all of the details of their decision making. (I wouldn't be able to.) There could in theory still be minutes of design meetings sitting in the bottom of someone's filing cabinet, but they are not accessible to us ... now.

My speculation is that the designers would have thought of plausible use-cases where enum values with mutable properties would be useful. And as @Sweeper points out, enum-based implementation of the singleton design pattern is one such use-case. Even the example that @aeberhart quotes in his answer can be read another way:

While fields of an enum do not have to be final, in the majority of cases we don't want our labels to change.

implies that in a minority of cases, they could want the labels to change. That's an argument for NOT requiring the label field in the example (and fields in general) to always be final ... at the language level.

To generalize, it is not a good thing for a program language design to not support (or forbid) constructs and usage patterns just because the designers don't like it. Or just because certain (so-called) experts endorse them as "best practice".




回答2:


It is best practice to use final, but (unfortunately) not enforced by the compiler.

This tutorial (https://www.baeldung.com/java-enum-values) states this as follows:

"Our label field is final. While fields of an enum do not have to be final, in the majority of cases we don't want our labels to change. In the spirit of enum values being constant, this makes sense."



来源:https://stackoverflow.com/questions/63532678/why-java-dont-force-to-use-final-with-enum-properties

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