Sub topic 13
Equality across subclasses: instanceof, getClass, and composition
This chapter assumes you can already write equals and hashCode for a final value class, and that you know the equals contract (reflexive, symmetric, transitive, consistent, false for null). It covers what happens when a subclass enters the picture, and which of three strategies to choose.
Why subclasses break equals
A subclass that only adds behavior is harmless. The trouble starts when a subclass adds a field that should take part in equality. No equals implementation can satisfy the contract for every such case. This is a known limitation of object-oriented languages. You can't extend an instantiable class with a value-bearing field and keep the contract. You choose which guarantee to give up, or you avoid inheritance.
Here is the failure from the earlier chapters, in a form you can run:
class Pt {
final int x, y;
Pt(int x, int y) { this.x = x; this.y = y; }
@Override
public boolean equals(Object o) {
if (!(o instanceof Pt)) return false;
Pt p = (Pt) o;
return p.x == x && p.y == y;
}
@Override
public int hashCode() { return 31 * x + y; }
}
class ColorPt extends Pt {
final String color;
ColorPt(int x, int y, String color) { super(x, y); this.color = color; }
@Override
public boolean equals(Object o) {
if (!(o instanceof ColorPt)) return false;
return super.equals(o) && ((ColorPt) o).color.equals(color);
}
@Override
public int hashCode() { return 31 * super.hashCode() + color.hashCode(); }
}
public class SymmetryDemo {
public static void main(String[] args) {
Pt p = new Pt(1, 2);
ColorPt cp = new ColorPt(1, 2, "red");
System.out.println(p.equals(cp)); // true
System.out.println(cp.equals(p)); // false
}
}p.equals(cp) runs Pt.equals, which sees a Pt with matching coordinates. cp.equals(p) runs ColorPt.equals, which rejects any argument that is not a ColorPt. The result depends on which side of the call you write, which is a symmetry violation. A collection can then give different answers depending on which object it happens to call equals on.
Strategy 1: instanceof
An instanceof check accepts the class itself and every subclass. It is correct when all of these hold:
- The class is
final, or no subclass adds state that matters for equality. - Equality is defined once, in the supertype, and subclasses do not override it.
Under those conditions, any two instances compare using the same rule, so symmetry and transitivity hold. The Point class in the earlier chapter works this way.
The tempting fix is to make ColorPt.equals ignore color when the other object is a plain Pt:
class ColorPt extends Pt {
final String color;
ColorPt(int x, int y, String color) { super(x, y); this.color = color; }
@Override
public boolean equals(Object o) {
if (!(o instanceof Pt)) return false;
if (!(o instanceof ColorPt)) return o.equals(this); // compare as a plain Pt
return super.equals(o) && ((ColorPt) o).color.equals(color);
}
@Override
public int hashCode() { return 31 * super.hashCode() + color.hashCode(); }
}This restores symmetry but breaks transitivity. Take a = new ColorPt(1, 2, "red"), b = new Pt(1, 2) and c = new ColorPt(1, 2, "blue"). Then a.equals(b) is true and b.equals(c) is true, but a.equals(c) is false. The hashCode is also inconsistent: a and b are equal but hash differently, so the contract is broken a second way. A subclass that inherits an instanceof check and adds state cannot be repaired by adding more instanceof checks.
Strategy 2: getClass
Comparing exact runtime classes makes objects of different classes never equal:
import java.util.HashSet;
import java.util.Set;
class Pt {
final int x, y;
Pt(int x, int y) { this.x = x; this.y = y; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pt p = (Pt) o;
return x == p.x && y == p.y;
}
@Override
public int hashCode() { return 31 * x + y; }
}
public class GetClassDemo {
public static void main(String[] args) {
Set<Pt> set = new HashSet<>();
set.add(new Pt(1, 2));
System.out.println(set.contains(new Pt(1, 2))); // true
System.out.println(set.contains(new Pt(1, 2) { })); // false
}
}This satisfies the contract: reflexive, symmetric, transitive and consistent for every subclass, including one that adds a field. The price is the Liskov substitution principle. Code that expects a Pt should work with any subclass of Pt. Here, an anonymous subclass with identical coordinates and no new state is not equal to a Pt. The same thing happens with framework-generated subclasses such as lazy-loading proxies, which silently fail equality checks against real instances.
| Property | `instanceof` | `getClass` |
|---|---|---|
| Symmetric and transitive with subclasses that add state | No | Yes |
| A subclass instance can equal a superclass instance | Yes | No |
| Works with generated proxies and anonymous subclasses | Yes | No |
| Safe if the class is `final` | Yes | Yes |
Strategy 3: composition
Effective Java's advice is to favor composition over inheritance. If you want "a point with a color", do not extend Point. Hold a Point in a field. There is no subclass relationship, so there is no cross-type equality to get wrong:
import java.util.Objects;
final class Point {
private final int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Point)) return false;
Point p = (Point) o;
return x == p.x && y == p.y;
}
@Override
public int hashCode() { return Objects.hash(x, y); }
}
final class ColorPoint {
private final Point point;
private final String color;
ColorPoint(int x, int y, String color) {
this.point = new Point(x, y);
this.color = Objects.requireNonNull(color);
}
Point asPoint() { return point; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ColorPoint)) return false;
ColorPoint c = (ColorPoint) o;
return point.equals(c.point) && color.equals(c.color);
}
@Override
public int hashCode() { return Objects.hash(point, color); }
}
public class CompositionDemo {
public static void main(String[] args) {
ColorPoint red = new ColorPoint(1, 2, "red");
ColorPoint blue = new ColorPoint(1, 2, "blue");
System.out.println(red.equals(blue)); // false
System.out.println(red.asPoint().equals(blue.asPoint())); // true
System.out.println(red.asPoint().equals(new Point(1, 2))); // true
}
}Both classes are final, so each uses a plain instanceof. You compare colored points by color and position, and you compare their Point views by position alone. Each comparison is explicit, so the code states what it means.
When a hierarchy is legitimate
Some hierarchies have a sound equality. The standard library does this with List: the List.equals contract is defined on the interface, and ArrayList equals LinkedList if they hold equal elements in the same order. Every implementation follows the same rule, so symmetry and transitivity hold across all of them.
You can copy this approach:
- Define equality once in an abstract base class or interface, based only on state every subtype shares.
- Make
equalsandhashCodefinalin the base so subclasses cannot change them. - Let subclasses add behavior, not state that affects equality.
Abstract base classes offer one more route. A class that can never be instantiated directly (abstract class Shape) can have subclasses with their own state, as long as no code compares a Shape reference to a different concrete type and expects a meaningful answer. The getClass check is a good fit for these, because each concrete type is its own equality domain.
The JDK itself has violations. java.sql.Timestamp extends java.util.Date and adds nanoseconds. Its Javadoc warns that equals is not symmetric with respect to Date. Do not copy that design.
Choosing a strategy
In practice:
- Prefer
finalvalue classes. Records are implicitly final, which is why their generatedequalshas no cross-subclass problem. - If you need "an X with extra data", use composition and expose a view method such as
asPoint(). - Use
getClassonly when you control the whole hierarchy and nothing generates subclasses at runtime. - Never override
equalsin a subclass that adds state while the parent usesinstanceof.
Common errors
- Adding a field to a subclass and extending
equalswithsuper.equals(o) && field == ...while the parent usesinstanceof. This breaks symmetry. - Making the subclass
equalslenient toward the parent to "fix" symmetry. This breaks transitivity. - Casting without a type check, so a
ClassCastExceptionappears when different types meet in a collection. - Using
getClassin a class whose instances are wrapped in framework proxies, so equal rows compare unequal. - Changing
equalsin a subclass but nothashCode, so equal objects hash differently.
Exercise
A class Money has an amount and is not final. A subclass TaggedMoney adds a String tag, and you want the tag to be part of equality. Money.equals uses instanceof. Name the contract property you break if TaggedMoney.equals is "amount and tag when comparing two TaggedMoney, amount only when comparing with a plain Money", and give a concrete triple of objects that shows it. What is a design that avoids the problem?
Show answer
The property broken is transitivity. With m = new Money(5), a = new TaggedMoney(5, "x") and b = new TaggedMoney(5, "y"): a.equals(m) is true and m.equals(b) is true, but a.equals(b) is false because the tags differ. Avoid it by making both classes final and having TaggedMoney hold a Money field (composition) with its own equals, or by dropping the tag from equality so the subclass adds no state that matters.