Video in progress
When writing equals() where inheritance is involved, which do you choose, getClass() or instanceof?
An equals written with instanceof breaks symmetry when parent and child classes are mixed. getClass() keeps symmetry, but it never considers a subclass equal, such as a Hibernate proxy.
📖 Answer
The equals contract: reflexive, symmetric, transitive, consistent, and x.equals(null) == false. Where there's inheritance, symmetry is the first thing to break.
class Point { int x, y;
public boolean equals(Object o) {
return o instanceof Point p && p.x == x && p.y == y;
}
}
class ColorPoint extends Point { String color;
public boolean equals(Object o) {
return o instanceof ColorPoint c && super.equals(c) && c.color.equals(color);
}
}
Point p = new Point(1, 2);
ColorPoint cp = new ColorPoint(1, 2, "red");
p.equals(cp); // true
cp.equals(p); // false: symmetry is broken
| Approach | Pro | Con |
|---|---|---|
getClass() != o.getClass() |
symmetry is guaranteed | a subclass (proxy) is never equal |
instanceof + final equals |
works with proxies | a subclass can't add new fields |
composition (a Point inside ColorPoint) |
no problem at all | a bit more code |
I usually make the value class final or use a record, and the question disappears. In a Hibernate entity, I write instanceof or Hibernate.getClass(), because a lazy proxy is a subclass of the entity.
Sign up to mark studied questions and save your progress.