ProgrammingHardIBM · Deloitte pattern
What is printed?
What is printed?
class Node {
Node next;
int val;
Node(int v) { val = v; }
public String toString() { return val + (next != null ? "->" + next : ""); }
}
// in main:
Node a = new Node(1), b = new Node(2), c = new Node(3);
a.next = b; b.next = c;
Object o = a;
System.out.println(o);- A. 1
- B. a reference-address string like Node@1a2b3c
- C. 1->2->3
- D. Compilation error: o has no toString
Correct answer: C. 1->2->3
println(o) calls o.toString() virtually; even though o's compile-time type is Object, its runtime type is Node, so Node's overridden toString() runs, recursively following next and producing "1->2->3".
More OOP with C++ and Java questions
- What is printed? java class A { final String tag() { return "A"; } } class B extends A { String tag(int x) { return "B" + x; } } // in…
- What is printed? cpp struct Base { virtual void f() { cout << "B"; } }; struct D1 : Base { void f() override { cout << "1"; } }; struct D2…
- What is printed? cpp struct Base { virtual void f() { cout << "B"; } }; struct D1 : Base { void f() override { cout << "X"; } }; struct D2…
- What happens when this is compiled? java interface A { default void m() { System.out.println("A"); } } interface B { default void m() {…
- What happens when Base b; is added inside main, right before the existing lines? cpp struct Base { virtual void f() = 0; }; struct Derived…
- What happens when this is compiled? cpp struct A { int x; }; struct B : A {}; struct C : A {}; struct D : B, C {}; int main() { D d; d.x =…