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 == otherwould be counter intuitive and violate the principle of least astonishment. Two enum constants are expected to beequalif 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(), andgetDeclaringClass().The JLS does not motivate the choice of making it final, but mentions equals in the context of enums here. Snippet: