According to Josh Bloch in Java:
There is no way to extend an instantiable class and add a value
component while preserving the equals contract, unless you are willing
to forgo the benefits of object-oriented abstraction
So here ‘s my case I had a class Foo that had overridden equals() and hashcode() as implemented by Intellij Idea . Now I have another class FooChild that extends Foo and adds a couple more fields to ‘Foo`. Now FindBugs is complaining about FooChild:
Class doesn’t override equals in superclass This class extends a class
that defines an equals method and adds fields, but doesn’t define an
equals method itself. Thus, equality on instances of this class will
ignore the identity of the subclass and the added fields. Be sure this
is what is intended, and that you don’t need to override the equals
method. Even if you don’t need to override the equals method, consider
overriding it anyway to document the fact that the equals method for
the subclass just return the result of invoking super.equals(o).
My question is “What is meant by equality on instances of this class will
ignore the identity of the subclass ? I understand the part about ignoring the added fields since no equals() method has been written for them yet .
If class
Foohas anequals()method, thenFooChildinherits it, meaning that if you compare two instances ofFooChildusingequals(), theFoo.equals()method will be called.If
FooChildhas any data members, then it’s probably possible for two instances ofFooChildto have the same values for members in theirFooparts, but different values for the members defined directly in the class. But theFoo.equals()method will only look at the members defined inFoo, and so would pronounce two such objects to beequals(), even though theirFooChildparts are different.This is why you need to override
equals()inFooChild.Now, what happens if you compare a
Fooand aFooChildusingequals(), when both classes have their own version ofequals()? It depends which object you callequals()on, and it depends on how you implement the twoequals()methods. Frankly, it’s a mess! That’s the meaning of the first quote, the one from Josh Bloch. It’s impossible to define these twoequals()methods so they always do the right thing. Therefore, it’s best to avoid the situation where one value class (i.e., a class whose identity is tied up with the values of its member variables) extends another value class.