Overriding and Access Levels: The Widening Rule
You'll learn why overriding methods must maintain or increase visibility — never reduce it.
The Core Rule
When you override a method from a superclass, Java enforces a simple but critical rule: the overriding method's access level must be at least as accessible as the original method. You can make it more accessible (wider), but you can never make it less accessible (narrower).
Think of it like a promise to the outside world. If your superclass advertised that a method is publicly available, a subclass can't secretly revoke that promise by making it private or protected. That would break the contract that clients of the superclass are relying on.
The Access Hierarchy (Narrowest to Widest)
private(narrowest)- Package-private (default)
protectedpublic(widest)
How the Rule Works
- If the superclass method is protected, you can override it as
protectedorpublic— but not package-private orprivate. - If the superclass method is public, you can only override it as
public. - If the superclass method is package-private, you can override it as package-private,
protected, orpublic.
Why This Matters
This rule ensures substitutability: any code that works with the superclass should also work seamlessly with a subclass instance. If you could narrow access during overriding, you'd break existing code that expects certain methods to be accessible.
Key Takeaway: When overriding methods, you can only maintain or widen access levels — never narrow them. This preserves the superclass contract and ensures safe polymorphism.