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
equalis becausesuper.equalsdoesn’t give the correct behaviour (right?).Or put another way, if
super.equalsgives 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 overridehashCode, too.