If I implement equals()
and hashCode()
in both the parent and child classes, is it necessary to call super.equals()
in equals()
in the child class, e.g.
public boolean equals(Object obj) {
if (obj.getClass() != ChildClass.class) {
return false;
}
return super.equals() && this.var == ((ChildClass) obj).var;
}
I am assuming that the parent class is not Object and is giving the correct definition of equals and hashCode.
No, that's not necessary, and would probably be wrong. Indeed, part of the reason why you're overriding equal
is because super.equals
doesn't give the correct behaviour (right?).
Or put another way, if super.equals
gives the correct behaviour, you probably don't need to go to the trouble of overriding it.
But if you are overriding equals
, then yes, you need to override hashCode
, too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With