Short question: Why does Java allow overriding equal(), 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 equal() should be a final method?
The book gives an example of a class A with equal() method and then a class AX extending A having its own equal() method which is different from the equal() method in A.
I will not go into details of equal() in A and equal() 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 equal() 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 equal(Object o) {
if (o == null || o.getClass() != getClass())
return false;
...
}
is wrong. I think this is precisely the proper way to deal with overriding equal(). The book cites Liskov substitution principle so I have looked at material at classes I have taken. And none of them mentions this Liskov substitution principle at least with this exact name. I suspect Liskov is not something standard enough that it comes into my syllabus or at least it is not as strict as it seems to be.
And I think Java makes it possible so Java allows overriding equal() for a reason. If it had taken into account Liskov substitution principle in the strict sense, then it would not have allowed overriding equal() and implicitly makes any implementation of equal() final at the compiler level. What are your thoughts?
I can think of a case where composition is simply not suitable, and overriding equal() 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.
Aucun commentaire:
Enregistrer un commentaire