ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
class Base {
    public String toString() { return "Base[" + describe() + "]"; }
    protected String describe() { return "generic"; }
}
class Sub extends Base {
    @Override
    protected String describe() { return "specific"; }
}
public class Main {
    public static void main(String[] args) {
        Object o = new Sub();
        System.out.println("Value: " + o);
    }
}
  1. A. Value: Base[generic]
  2. B. Value: Base[specific]
  3. C. Value: Sub[specific]
  4. D. Compile-time error: describe() is protected, so toString() of Object cannot see it

Correct answer: B. Value: Base[specific]

String concatenation with + calls toString() on o, dynamically dispatched to the most-derived override — but Sub doesn't override toString(), so it's Base's toString() that runs, calling describe() polymorphically, which (since the real object is a Sub) dispatches to Sub's override, returning "specific". Result: Base[specific].

More OOP with C++ and Java questions

Exams that ask this topic