✏️ Explanatory Question

[Inheritance]

What will happen if method void show() in subclass Car is given access specifier as private?

👁 0 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

A compile-time error will occur because an overridden method cannot have weaker access privilege than the superclass method.

Understanding the Original Code:

In the superclass Vehicle, the method is:

public void show() { ... }

This method is inherited and overridden in subclass Car.

Original Overridden Method:

public void show() { super.show(); ... }

What Happens if show() Becomes Private?

private void show() { ... }

Java will generate a:

Compile-Time Error

Reason:

While overriding a method:

Child class cannot reduce the visibility of the inherited method.

Access Modifier Rule in Method Overriding:

Superclass Method Allowed in Child?
public Only public ✅
protected protected or public ✅
default default/protected/public ✅
private Cannot be overridden ❌

Why Error Occurs?

In superclass:

public void show()

In subclass:

private void show()

Here, access level changes from:

public → private

This reduces visibility, which is not allowed in Java method overriding.

Error Message:

Cannot reduce the visibility of the inherited method from Vehicle

Important Concept:

Overridden method must have: same or higher accessibility

Correct Possibilities:

Superclass Method Valid Child Method Access
public public only
protected protected/public

Final Conclusion:

  • Changing show() in subclass to private causes compile-time error.
  • Visibility of overridden method cannot be reduced.
  • Since superclass method is public, subclass method must also remain public.