Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling super.equals and super.hashCode in child class?

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.

like image 753
BJ Dela Cruz Avatar asked Apr 20 '12 21:04

BJ Dela Cruz


1 Answers

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.

like image 85
Norman Gray Avatar answered Sep 23 '22 08:09

Norman Gray