ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
class Base {
    void show() { System.out.print("Base"); }
}
class Sub extends Base {
    void show() { System.out.print("Sub"); }
    void show(String s) { System.out.print("Sub:" + s); }
}
public class Main {
    public static void main(String[] args) {
        Base b = new Sub();
        b.show();
    }
}
  1. A. Base
  2. B. Sub
  3. C. Compile-time error: show() is ambiguous since Sub overloads it too
  4. D. Sub:null

Correct answer: B. Sub

Sub.show() with no arguments has the identical signature to Base.show(), so it truly overrides it (the extra overload show(String) is a separate, additional method). b.show() with no arguments dispatches dynamically to the real object's class, Sub, printing Sub.

More OOP with C++ and Java questions

Exams that ask this topic