Course contentsShow
← Java
Lesson 420 of 2,87010. Inheritance FundamentalsFree lesson

Access Modifier Rules for Overriding

Understand that overriding methods must be at least as accessible as the superclass method, never more restrictive.

Access Modifier Rules for Overriding

What you'll learn: When overriding a method, you can't make it more restrictive—only equally or more accessible than the parent version.


The Golden Rule

When you override a method from a superclass, Java enforces a critical rule: the overriding method must be at least as accessible as the method it's replacing. You can make it more open, but never less open.

Think of it like a business policy: if your company headquarters promises customers "walk-in access Monday through Friday," a local branch can't suddenly say "appointment only." They can stay the same or become more welcoming (like 24/7 access), but never more restrictive.

Why This Rule Exists

Imagine a superclass reference pointing to a subclass object. If the superclass method is public, callers expect to access it freely. If the subclass could secretly make it private, that would break the contract—code that worked with the parent type would mysteriously fail with the child type.

The Hierarchy (Least to Most Accessible)

  1. private (not inherited, so can't be overridden anyway)
  2. package-private (default)
  3. protected
  4. public

Valid Overriding Examples

  • Superclass: protected → Subclass: protected ✅ (same)
  • Superclass: protected → Subclass: public ✅ (more open)
  • Superclass: package-private → Subclass: public ✅ (more open)

Invalid Overriding Examples

  • Superclass: public → Subclass: protected ❌ (more restrictive)
  • Superclass: protected → Subclass: package-private ❌ (more restrictive)

If you try to compile code that violates this rule, Java will throw a compilation error telling you the overriding method is attempting to reduce visibility.


Key Takeaway: When overriding, you can maintain or increase access (like protected → public), but never decrease it—the subclass method must be at least as accessible as the superclass version.