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);
}
}- A. Value: Base[generic]
- B. Value: Base[specific]
- C. Value: Sub[specific]
- 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
- What is printed? cpp struct A { A() { cout << "A"; } }; struct B { B() { cout << "B"; } }; struct C : A, B { C() { cout << "C"; } }; int…
- What is printed? cpp struct Animal { virtual std::string sound() const { return "..."; } }; struct Dog : Animal { std::string sound()…
- What is printed? cpp struct Shape { virtual double area() const = 0; void report() const { std::cout << "Area: " << area(); } }; struct…
- What is the behavior? cpp struct Base { ~Base() { std::cout << "~Base "; } // NOT virtual }; struct Derived : Base { int data = new…
- What is printed? cpp struct A { virtual void f(int x) { std::cout << "A::f(int) " << x; } }; struct B : A { virtual void f(double x) {…
- What is printed? cpp struct Base { virtual void f() const { std::cout << "Base::f const"; } }; struct Derived : Base { void f() {…