views:

213

answers:

5
@Override
public boolean equals(Object otherObject) 

is not allowed in Java 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.

A: 

It is precisely because the Java designers could not think of any conceivable use case for overriding Enum.equals(Object) that that method is declared as final - so that such overriding would be impossible.

jhominal
+2  A: 

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.

Stephen C
+6  A: 

The intuition of clients that deal with enum constants is that two constants are equal if and only if they are the same constant. Thus any other implementation than return this == other would be counterintuitive and 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.

aioobe
A: 

I must confess enums are the last thing I would want to override equals() in.

I think the reason equals() is final in enums is that Java encourages == for enum comparison, and the implementation of equals() in enums simply uses it, So allowing equals() from being overridden is to prevent == and equals() from behaving differently, which is something other developers would not expect.

Oak
+3  A: 

Just imagine (be aware - political correctness was not a requirement ;) ):

public enum Communism { ALL, ENUMS, ARE, EQUAL;

    // won't compile!
    public boolean equal(Object other) {
      return true;
    }
}

and later on, somewhere else:

Communism commie = getCommie();
switch (commie) {
  case ALL: System.out.println("We're all the same!");break;
  case ENUMS:
  case ARE:
  case EQUAL: System.out.println("There's no doubt about it (unreachable!)"; break;
}

This is an extreme example, but it shows that overriding equals would lead to unexpected behaviuor in other parts of the code.

Andreas_D
This is the best response. Rather than pointing out the absence of a use case, Andreas_D gave an excellent counter-example. Good Job!
emory