ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
class Base {
    protected void show() { System.out.println("Base.show"); }
}
class Derived extends Base {
    @Override
    public void show() { System.out.println("Derived.show"); }
}
Is the override in Derived legal, and why?
  1. A. No: public cannot override protected
  2. B. Yes: an override may widen (increase) access, but never narrow it
  3. C. Yes, but only if both are declared final
  4. D. No: access modifiers must match exactly between override and base

Correct answer: B. Yes: an override may widen (increase) access, but never narrow it

Java allows an overriding method to widen visibility (protected -> public here) but never to narrow it (e.g. protected -> private would be illegal), because callers relying on the base class's visibility contract must still be able to call the method through any subclass instance.

More OOP with C++ and Java questions

Exams that ask this topic