Why Java does not allow overriding equals(Object) in an Enum?
I've noticed that the following snippet...
@Override
public boolean equals(Object otherObject) {
...
}
...is not allowed for an Enum, since the method equals(Object x)
is defined as final
in Enum
. Why is this so?
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.
Same reasoning applies to hashCode()
, clone()
, compareTo(Object)
, name()
, ordinal()
, and getDeclaringClass()
.
While the JLS does not motivate the choice of making it final, but mentions equals in the context of enums here. Snippet:
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.
There is already provides a strong intuitive notion of what it means for instances (values) of an enum
to be equal. Allowing the overloading the equals
method would lead to that notion being violated, leading to unexpected behavior, bugs and so on.
正是因为Java设计人员无法想出任何可覆盖的Enum.equals(Object)的用例,所以这种方法被声明为final - 因此这种重写将是不可能的。
链接地址: http://www.djcxy.com/p/91838.html上一篇: java中的单例