ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
class Base {
    Base() {
        System.out.print("Base-ctor ");
    }
    static { System.out.print("Base-static "); }
}
class Sub extends Base {
    static { System.out.print("Sub-static "); }
    Sub() { System.out.print("Sub-ctor "); }
}
public class Main {
    public static void main(String[] args) {
        System.out.print("start ");
        new Sub();
    }
}
  1. A. Base-static Sub-static start Base-ctor Sub-ctor
  2. B. start Base-static Sub-static Base-ctor Sub-ctor
  3. C. start Base-ctor Sub-ctor Base-static Sub-static
  4. D. Base-static Sub-static Base-ctor Sub-ctor start

Correct answer: B. start Base-static Sub-static Base-ctor Sub-ctor

main's own body starts running first, printing start. Only when new Sub() is actually reached does the JVM load (if not already loaded) and statically initialise Base then Sub, in superclass-first order, printing Base-static then Sub-static; then object construction runs, Base-ctor then Sub-ctor.

More OOP with C++ and Java questions

Exams that ask this topic