ProgrammingVery hardProduct-company placement · Java

What is printed?

What is printed?
class Pt {
    int x;
    Pt(int x) { this.x = x; }
    public boolean equals(Object o) { return o instanceof Pt && ((Pt) o).x == x; }
    public int hashCode() { return x; }
}
class CPt extends Pt {
    String c;
    CPt(int x, String c) { super(x); this.c = c; }
    public boolean equals(Object o) {
        return o instanceof CPt && super.equals(o) && ((CPt) o).c.equals(c);
    }
}
// in main:
Pt p = new Pt(1);
CPt q = new CPt(1, "red");
System.out.print(p.equals(q) + " " + q.equals(p));
  1. A. true true
  2. B. false false
  3. C. true false
  4. D. false true

Correct answer: C. true false

A CPt is a Pt, so p.equals(q) only compares x (true); but p is not a CPt, so q.equals(p) is false. Adding a field in a subclass this way breaks the symmetry required by the equals contract.

More OOP with C++ and Java questions

Exams that ask this topic