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);
  1. A. 1
  2. B. a reference-address string like Node@1a2b3c
  3. C. 1->2->3
  4. 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

Exams that ask this topic