ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
class Base {
    void greet() { System.out.print("Base "); helper(); }
    private void helper() { System.out.print("BaseHelper "); }
}
class Sub extends Base {
    private void helper() { System.out.print("SubHelper "); }
}
public class Main {
    public static void main(String[] args) { new Sub().greet(); }
}
  1. A. Base SubHelper
  2. B. SubHelper Base
  3. C. Base BaseHelper
  4. D. Compile-time error: helper() is redeclared with the same signature in Sub

Correct answer: C. Base BaseHelper

private methods are not inherited and cannot be overridden; Sub.helper() is a completely separate, unrelated method confined to Sub's own scope (declaring it is legal, not a redefinition error). Base.greet()'s internal call to helper() can only ever resolve to Base's own private helper(), printing Base BaseHelper regardless of the actual object's class.

More OOP with C++ and Java questions

Exams that ask this topic