Why Java does not allow overriding equals(Object) in an Enum?

前端 未结 5 1495
一整个雨季
一整个雨季 2020-12-03 04:18

I\'ve noticed that the following snippet...

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

...is not allowed for an Enum,

5条回答
  •  臣服心动
    2020-12-03 05:10

    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().


    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.

提交回复
热议问题