Video in progress

Strong Junior 🧱 OOP and SOLID

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 of instanceof, 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 ColorPoint hold a Point field instead of inheriting, which is the cleanest way;
  • make the parent class final or turn it into a record; 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.