Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 846
Ashwin Prabhu Avatar asked Jun 03 '10 09:06

Ashwin Prabhu


People also ask

Can we override enum in Java?

Enums are exactly final inner classes that extends java. lang. Enum<E> . You cannot extend, override or inherit an enum .

Can we use equals with enum in Java?

equals method uses == operator internally to check if two enum are equal. This means, You can compare Enum using both == and equals method.

Can we override the equals method in Java?

You can override the equals method on a record, if you want a behavior other than the default. But if you do override equals , be sure to override hashCode for consistent logic, as you would for a conventional Java class.

Does enum have equals method?

The equals() method of Enum class returns true if this enum object is same as the defined object.


2 Answers

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.

like image 160
aioobe Avatar answered Oct 05 '22 15:10

aioobe


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.

like image 25
Stephen C Avatar answered Oct 05 '22 13:10

Stephen C