ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
class Base {
    Base(String tag) { System.out.print("Base:" + tag + " "); }
}
class Sub extends Base {
    Sub() { super(makeTag()); System.out.print("Sub "); }
    static String makeTag() { return "generated"; }
}
public class Main {
    public static void main(String[] args) { new Sub(); }
}
  1. A. Sub Base:generated
  2. B. Base:generated Sub
  3. C. Compile-time error: cannot call a static method before super() finishes
  4. D. Base:null Sub

Correct answer: B. Base:generated Sub

Arguments to super(...) must be evaluable before the superclass constructor actually runs, and static methods of the subclass are allowed there since they don't depend on instance state. makeTag() runs first, returning "generated"; Base's constructor then prints Base:generated; only afterward does Sub's own body print Sub.

More OOP with C++ and Java questions

Exams that ask this topic