ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
class Base {
    void process() {
        System.out.print("Base.process ");
        validate();
    }
    protected void validate() { System.out.print("Base.validate "); }
}
class Sub extends Base {
    @Override
    protected void validate() {
        System.out.print("Sub.validate ");
        throw new IllegalStateException("bad");
    }
}
public class Main {
    public static void main(String[] args) {
        try {
            new Sub().process();
        } catch (IllegalStateException e) {
            System.out.print("caught:" + e.getMessage());
        }
    }
}
  1. A. Base.process Base.validate
  2. B. Base.process Sub.validate caught:bad
  3. C. Compile-time error: validate() cannot throw since Base's version doesn't declare it
  4. D. Sub.validate Base.process caught:bad

Correct answer: B. Base.process Sub.validate caught:bad

process() is inherited unchanged and calls validate() polymorphically; since the real object is a Sub, it dispatches to Sub's override, printing Sub.validate, which then throws. IllegalStateException is unchecked, so overriding with a throw needs no throws declaration; it propagates up and is caught in main, printing caught:bad.

More OOP with C++ and Java questions

Exams that ask this topic