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));- A. true true true
- B. false false false
- C. true false false
- 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
- What is printed? java List<String> l = new ArrayList<>(List.of("pear", "fig", "apple", "kiwi", "date"))…
- What is printed? java // static methods of the main class: static void f(Object o) { System.out.print("Object"); } static void f(String s)…
- What is printed? java // static method of the main class: static void f(Object... a) { System.out.print(a == null ? "N " : a.length + "…
- What is printed? java interface Shape { double area(); } class Sq implements Shape { double area() { return 4; } } // in main: Shape s =…
- Which declaration is LEGAL inside an abstract Java class?
- Which line fails to compile? java class Outer { int x = 1; class In { int get() { return x; } } static class SN { int get() { return 2; }…