ProgrammingHardHCL · Tech Mahindra pattern
What is printed?
What is printed?
class Node {
Node next;
int val;
Node(int v) { val = v; }
@Override
public String toString() { return "N(" + val + ")"; }
}
class NamedNode extends Node {
String name;
NamedNode(int v, String n) { super(v); name = n; }
@Override
public String toString() { return name + ":" + super.toString(); }
}
// in main:
Node n = new NamedNode(7, "x");
System.out.println(n);- A. N(7)
- B. x:N(7)
- C. Compile-time error: println cannot resolve the overridden toString
- D. x
Correct answer: B. x:N(7)
println(Object) calls toString() on the argument, which dispatches dynamically to NamedNode's override, returning "x:" plus the result of super.toString() (an explicit, statically-bound call to Node's own toString, "N(7)"), giving "x:N(7)".
More OOP with C++ and Java questions
- What is printed? java class Employee { double bonus() { return 1000; } double pay() { return 50000 + bonus(); } } class Manager extends…
- What is printed? cpp struct Base { Base() { cout << "CtorBase "; } virtual ~Base() { cout << "DtorBase "; } }; struct Derived : Base {…
- What is printed? cpp struct Shape { virtual double area() const { return 0; } virtual void print() const { cout << "Area: " << area(); }…
- What is printed? java class A { public String toString() { return "A"; } } class B extends A { } class C extends B { public String…
- What is printed? cpp struct A { virtual void f() { cout << "A"; } }; struct B : A { void f() override { cout << "B"; A::f(); } }; int…
- What is printed? java class Vehicle { int wheels() { return 4; } } class Motorcycle extends Vehicle { @Override int wheels() { return 2; }…