ProgrammingVery hardProduct-company placement · GATE CS
What is printed?
What is printed?
class P {
int v;
P(int v) { this.v = v; }
public boolean equals(P o) { return o.v == v; }
}
// in main:
List<P> list = new ArrayList<>();
list.add(new P(1));
System.out.print(new P(1).equals(new P(1)) + " " + list.contains(new P(1)));- A. true true
- B. false false
- C. true false
- D. false true
Correct answer: C. true false
equals(P) overloads rather than overrides equals(Object). The direct call has a P argument and picks the overload (true), but ArrayList.contains calls equals(Object), which is still Object's identity check (false). @Override would have caught this.
More OOP with C++ and Java questions
- Which lines fail to compile? cpp struct M { int v; M(int x) : v(x) { } M operator+(const M& o) const { return M(v + o.v); } }; int main()…
- Why does the C++ standard reject a copy constructor declared as T(T other) for a class T?
- A drawing program uses the Visitor pattern: Shape has accept(Visitor v), and Circle implements it as v.visit(this). Visitor has overloads…
- How many of these statements about Java (9 or later) are correct? 1. An interface can declare instance fields. 2. An abstract class can…
- A UI component registers itself as an observer of a long-lived global EventBus when it is created but never unregisters. Screens using…
- A vending machine object behaves differently when Idle, HasCoin or Dispensing, and each state object decides which state comes next. A…