为什么Java不强制将final与枚举属性一起使用 [英] Why Java don't force to use final with enum properties

查看:40
本文介绍了为什么Java不强制将final与枚举属性一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们在这里查看我的枚举定义:

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
    }

通常,我知道我们不应该实现这样的代码.为了防止这种情况,为什么Java不像Java那样使用接口的属性将 final 用作 final int index .有人可以解释吗?

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?

推荐答案

诸如为什么Java不强制对 enum 属性使用 final 的问题"之类的问题;只有一个正确答案:

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

因为Java设计人员没有那样设计.

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.

我的猜测是,设计师会想到合理的用例,其中具有可变属性的 enum 值将很有用.正如@Sweeper指出的那样,基于 enum 的单例设计模式的实现就是这样一种用例.甚至是示例,@ aeberhart在他的答案中引用的例子也可以用另一种方式解读:

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:

枚举的字段不必为 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.

暗示在少数情况下,他们可能希望更改标签.这是不要求示例中的 label 字段(以及一般字段)在语言级别始终为 final ...的论据.

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".

这篇关于为什么Java不强制将final与枚举属性一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆