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;
}
}- A. Neither is broken
- B. A's equals() is broken because it special-cases B
- C. B's equals() is broken: it accepts any A, breaking symmetry with plain A objects that never special-case B
- 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
- What is printed? java class Version { int major, minor; Version(int ma, int mi) { major = ma; minor = mi; } @Override public boolean…
- What is printed? java public class Main { static int f() { int x = 10; try { return x; } finally { x = 20; } } public static void…
- What is printed? java public class Main { public static void main(String[] a) { try { System.out.print("A"); throw new RuntimeException()…
- Does this compile? java class MyException extends Exception {} class Demo { void risky() throws MyException { throw new MyException(); }…
- Does this compile? java class Demo { void risky() { throw new IllegalArgumentException(); } void call() { risky(); } }
- What is printed? java public class Main { public static void main(String[] a) { int[] arr = {1, 2, 3}; try { System.out.print(arr[5]); }…