Short question: Why does Java allow overriding equals(), why is it not final?
I am reading Effective Java 2nd edition by Joshua Bloch. I am a bit baffled by the conclusion that
There is no way to extend an instantiable class and add a value component while preserving the equals contract
Is not it saying the same as equals() should be a final method?
The book gives an example of a class A with equals() method and then a class AX extending A having its own equals() method which is different from the equals() method in A.
I will not go into details of equals() in A and equals() in AX, but it suffices to say that they are different. Therefore we have inter-operatability problem which guarantees violation of transitivity and/or symmetry (maybe even something else) of equals() when we mix different implementations of A in some contexts (especially HashSet, HashMap type).
Thinking further, I don't think I can agree with with the conclusion that having something like
public boolean equals(Object o) {
if (o == null || o.getClass() != getClass())
return false;
...
}
is wrong. I think this is precisely the proper way to deal with overriding equals().
Java makes it possible so Java allows overriding equals() for a reason. If it had taken into account Liskov substitution principle in the strict sense, then it would not have allowed overriding equals() and implicitly makes any implementation of equals() final at the compiler level. What are your thoughts?
I can think of a case where composition is simply not suitable, and overriding equals() is the best option. This is the case where the class A is to be made persistent in a database and the context implies that there is no collection having both an implementation of A and subclasses of A such as AX.