为什么Java不允许在枚举中覆盖equals(Object)? [英] Why Java does not allow overriding equals(Object) in an Enum?

查看:563
本文介绍了为什么Java不允许在枚举中覆盖equals(Object)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到以下片段...

I've noticed that the following snippet...

@Override
public boolean equals(Object otherObject) {
    ...
}

...不允许一个枚举,因为方法 equals(Object x) final /download.oracle.com/javase/6/docs/api/java/lang/Enum.html#equals%28java.lang.Object%29rel =noreferrer> 枚举 。为什么这样呢

...is not allowed for an Enum, since the method equals(Object x) is defined as final in Enum. Why is this so?

我不能想到任何需要覆盖枚举的 equals(Object)的用例。我只是好奇地知道这个行为背后的原因。

I cannot think of any use case which would require overriding equals(Object) for Enum. I'm just curious to know the reasoning behind this behavior.

推荐答案

只有其他将是反直觉的,违反最不惊讶的原则。如果且仅当它们是相同的对象并且覆盖此行为的能力才容易出错,则两个枚举常量将被预期为等于

Anything but return this == other would be counter intuitive and violate the principle of least astonishment. Two enum constants are expected to be equal if and only if they are the same object and the ability to override this behavior would be error prone.

相同的推理适用于 hashCode() clone() compareTo(Object) name() ordinal() getDeclaringClass()

Same reasoning applies to hashCode(), clone(), compareTo(Object), name(), ordinal(), and getDeclaringClass().

虽然JLS没有激励选择使它成为最终,但是在枚举的上下文中等于此处。代码段:

While the JLS does not motivate the choice of making it final, but mentions equals in the context of enums here. Snippet:


枚举中的equals方法是一种最终的方法只需在其参数上调用 super.equals 并返回结果,从而执行身份比较。

The equals method in Enum is a final method that merely invokes super.equals on its argument and returns the result, thus performing an identity comparison.

这篇关于为什么Java不允许在枚举中覆盖equals(Object)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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