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
}- A. Compiles fine, Derived.show() is simply less visible now
- B. Compiles fine, but calling show() via Base reference uses Base::show instead
- C. Runtime error only when show() is actually called
- 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
- What is printed? java class Base { void greet(Object o) { System.out.print("Object "); } } class Derived extends Base { void greet(String…
- What is printed? java class Base { static void show() { System.out.print("Base.static "); } } class Derived extends Base { static void…
- What is printed? java class Base { protected int code = 1; } class Derived extends Base { int code = 2; } // in main: Base b = new…
- What is printed? java class Vehicle { void start() { System.out.print("Vehicle starts "); } } interface Electric { default void start() {…
- What is printed? java interface Counter { int next(); private int helper() { return 100; } default int nextPlusHelper() { return next() +…
- What is printed? cpp class Account { double balance = 0; friend void deposit(Account& a, double amt); public: double getBalance() const {…