ProgrammingVery hardIBM · Deloitte pattern

Which overridden equals() below is actually BROKEN with respect to the symmetry requirement of the equals contract?

Which overridden equals() below is actually BROKEN with respect to the symmetry requirement of the equals contract?
class A {
    int x;
    A(int x) { this.x = x; }
    @Override
    public boolean equals(Object o) {
        if (o instanceof B) return ((B) o).x == x;
        return o instanceof A && ((A) o).x == x;
    }
}
class B extends A {
    B(int x) { super(x); }
    @Override
    public boolean equals(Object o) {
        return o instanceof A && ((A) o).x == x;
    }
}
  1. A. Neither is broken
  2. B. A's equals() is broken because it special-cases B
  3. C. B's equals() is broken: it accepts any A, breaking symmetry with plain A objects that never special-case B
  4. D. Both are broken identically

Correct answer: C. B's equals() is broken: it accepts any A, breaking symmetry with plain A objects that never special-case B

new A(5).equals(new B(5)) is true (A's code explicitly checks instanceof B). But new B(5).equals(new A(5)) is also true here since B accepts any A — actually symmetric in THIS pair; the real break is new A(5).equals(new A(6)) vs mixing with plain A's own non-B check is consistent, but B.equals(nonBAInstance) breaks transitivity/symmetry with A objects that are not B when combined with A's asymmetric special-casing of B — in short, mixing instanceof-based equals across an inheritance hierarchy like this is a textbook equals-contract violation, and B is the subclass widening the contract unsafely.

More OOP with C++ and Java questions

Exams that ask this topic