ProgrammingHardHCL · Tech Mahindra pattern

What is printed?

What is printed?
class Base {
    public void show() { System.out.print("Base "); }
}
class Derived extends Base {
    protected void show() { System.out.print("Derived "); } // narrows access
}
  1. A. Compiles fine, Derived.show() is simply less visible now
  2. B. Compiles fine, but calling show() via Base reference uses Base::show instead
  3. C. Runtime error only when show() is actually called
  4. D. Compilation error: cannot reduce visibility of an inherited method (public to protected) when overriding

Correct answer: D. Compilation error: cannot reduce visibility of an inherited method (public to protected) when overriding

Java forbids an overriding method from having a MORE RESTRICTIVE access modifier than the method it overrides. Base::show is public, so Derived::show must be public too (or could be widened, but never narrowed); reducing it to protected is a compile-time error.

More OOP with C++ and Java questions

Exams that ask this topic