ProgrammingVery hardProduct-company placement · Java

What is printed?

What is printed?
class P {
    int id;
    P(int id) { this.id = id; }
    public boolean equals(P o) { return o != null && id == o.id; }
}
// in main:
P a = new P(1), b = new P(1);
List<P> l = new ArrayList<>(List.of(a));
System.out.print(a.equals(b) + " " + l.contains(b) + " " + ((Object) a).equals(b));
  1. A. true true true
  2. B. false false false
  3. C. true false false
  4. D. true false true

Correct answer: C. true false false

equals(P) OVERLOADS rather than overrides equals(Object). a.equals(b) picks the overload at compile time (true), but List.contains and a call through an Object reference use equals(Object), inherited from Object: identity, false.

More OOP with C++ and Java questions

Exams that ask this topic