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?- A. No: public cannot override protected
- B. Yes: an override may widen (increase) access, but never narrow it
- C. Yes, but only if both are declared final
- 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
- What is printed? java class Calculator { int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } int…
- What is printed? java class Shape { void draw() { System.out.println("Shape.draw"); } } class Circle extends Shape { void draw() {…
- Does this compile? java class Base { void greet() { System.out.println("Base.greet"); } } class Derived extends Base { @Override void…
- What is printed? java class Repo<T> { private List<T> items = new ArrayList<>(); void add(T item) { items.add(item); } T get(int i) {…
- What is printed? java interface Shape { double area(); default String describe() { return "Shape with area " + area(); } } class Square…
- What is printed? cpp struct A { int x = 10; virtual int getX() { return x; } }; struct B : A { int x = 20; int getX() override { return x…