Advertisement
Advanced Java, equals(), hashCode() & toString() Contracts

How would you correctly implement equals() and hashCode() for a class in an inheritance hierarchy where the superclass itself defines meaningful equality-relevant fields, without breaking the contract when subclasses add their own fields?

Short answer

The generally recommended approach when meaningful inheritance-based equality is truly needed is for the subclass's equals() to first call super.equals(o) (verifying the superclass's own fields match, which itself typically requires getClass() equality further up to preserve…

Save Java mock interview
Advertisement
AModel answer
The generally recommended approach when meaningful inheritance-based equality is truly needed is for the subclass's equals() to first call super.equals(o) (verifying the superclass's own fields match, which itself typically requires getClass() equality further up to preserve symmetry/transitivity) before additionally comparing its own new fields, with hashCode() similarly combining super.hashCode() together with the subclass's own new fields via the standard combining formula -- however, this pattern is inherently fragile precisely because of the equals()/inheritance tension discussed earlier (getClass() versus instanceof), which is why Effective Java's ultimate guidance remains to prefer composition over inheritance for value classes whenever equality semantics matter, sidestepping this fragility entirely.
public class Point {
    protected final int x, y;
    public boolean equals(Object o) {
        if (!(o instanceof Point p) || getClass() != o.getClass()) return false;
        return x == p.x && y == p.y;
    }
    public int hashCode() { return Objects.hash(x, y); }
}

public class ColorPoint extends Point {
    private final String color;
    @Override
    public boolean equals(Object o) {
        if (!super.equals(o)) return false;  // checks x, y AND getClass() via super
        ColorPoint cp = (ColorPoint) o;
        return color.equals(cp.color);
    }
    @Override
    public int hashCode() { return 31 * super.hashCode() + color.hashCode(); }
}
Real-world example
A shape hierarchy where ColorPoint extends Point calls super.equals() and super.hashCode() as part of its own overrides, correctly incorporating the inherited fields' contribution to equality while still adding its own color field, though the team documents this as a deliberately accepted trade-off given the getClass()-based strictness this requires.
Likely follow-ups
  • What specific transitivity violation would occur if ColorPoint used instanceof instead of relying on super.equals()'s getClass() check?
  • At what point does this inheritance-based equals() complexity suggest a composition-based redesign would be simpler overall?
Related topics