Video in progress
How does overriding equals() separately in a parent and a child class break symmetry?
If Point.equals compares only x, y while ColorPoint.equals also compares the color, then point.equals(colorPoint) is true but colorPoint.equals(point) is false. That breaks the symmetry rule of the equals contract, and collections start behaving unexpectedly.
📖 Answer
class Point {
final int x, y;
@Override public boolean equals(Object o) {
return o instanceof Point p && p.x == x && p.y == y;
}
}
class ColorPoint extends Point {
final String color;
@Override public boolean equals(Object o) {
return o instanceof ColorPoint cp && super.equals(cp) && cp.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
The consequence: the result of List.contains depends on the order of the elements in the list, and duplicates appear inside a HashSet.
Ways to fix it:
- use
getClass() != o.getClass()instead ofinstanceof, so different classes are never equal. Symmetry is restored, but LSP is weakened a bit (a child object is never equal to the parent); - composition: have
ColorPointhold aPointfield instead of inheriting, which is the cleanest way; - make the parent class
finalor turn it into arecord; records can't be extended, so the problem goes away.
In short: with inheritance that adds state (a field), writing a correct equals is almost impossible.
Sign up to mark studied questions and save your progress.