ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
class Base {
    protected int val;
    Base(int v) {
        val = v;
        System.out.print("Base(" + val + ") ");
    }
}
class Derived extends Base {
    Derived() {
        super(compute());
        System.out.print("Derived ");
    }
    static int compute() {
        System.out.print("compute ");
        return 42;
    }
}
public class Main {
    public static void main(String[] args) { new Derived(); }
}
  1. A. Base(42) compute Derived
  2. B. compute Base(42) Derived
  3. C. Derived compute Base(42)
  4. D. Compile-time error: cannot call a static method as a super() argument

Correct answer: B. compute Base(42) Derived

Arguments to super(...) are evaluated before the superclass constructor is entered, so compute() runs first, printing compute and returning 42. Then Base(42) runs, printing Base(42). Only after super() fully completes does Derived's own constructor body continue, printing Derived.

More OOP with C++ and Java questions

Exams that ask this topic