Course contentsShow
← Java
Lesson 550 of 2,87013. The Object Class and Common MethodsFree lesson

equals and hashCode with Inheritance

Understand why equals is dangerous to override in hierarchies and how getClass vs instanceof affects the symmetry requirement.

equals and hashCode with Inheritance

You'll learn why overriding equals in class hierarchies is risky and how getClass() vs instanceof affects the symmetry requirement.

The Danger Zone

When you override equals in a parent class and then create subclasses, you face a dilemma that can break the symmetry requirement (x.equals(y) must equal y.equals(x)).

Consider a Point class with x and y coordinates. You create a subclass ColorPoint that adds a color field. Now the trouble begins:

Using instanceof

If Point.equals() uses instanceof, it only checks x and y. A Point might equal a ColorPoint, but the ColorPoint.equals() that also checks color will return false in reverse—breaking symmetry.

Point p = new Point(1, 2);
ColorPoint cp = new ColorPoint(1, 2, RED);

p.equals(cp)   // true (only checks x, y)
cp.equals(p)   // false (color doesn't match)
// SYMMETRY BROKEN!

Using getClass()

If you use getClass() to ensure exact type matching, symmetry is preserved—but you lose polymorphism. A Point can never equal a ColorPoint, even with identical coordinates. Liskov Substitution Principle suffers.

The Painful Truth

There's no perfect solution when subclasses add value fields. Joshua Bloch's advice: favor composition over inheritance for classes that override equals. Make your equals-overriding classes final, or don't add value fields in subclasses.

Key Takeaway: Overriding equals in class hierarchies is fraught with danger—instanceof breaks symmetry when subclasses add fields, while getClass() breaks polymorphic equality. Design with composition or make classes final when possible.