ProgrammingVery hardProduct-company placement · Java

What is printed?

What is printed?
class P {
    int x;
    P(int x) { this.x = x; }
    public boolean equals(Object o) {
        return o != null && getClass() == o.getClass() && ((P) o).x == x;
    }
    public int hashCode() { return x; }
}
class Q extends P { Q(int x) { super(x); } }
// in main:
System.out.print(new P(1).equals(new Q(1)) + " " + new Q(1).equals(new Q(1)));
  1. A. false true
  2. B. true true
  3. C. false false
  4. D. true false

Correct answer: A. false true

An equals based on getClass() treats objects of different runtime classes as unequal, even a subclass that adds nothing. instanceof would have returned true for P vs Q.

More OOP with C++ and Java questions

Exams that ask this topic