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

Access Modifiers and Inherited Members

Understand which members are visible in subclasses: public, protected, package-private, but not private.

Access Modifiers and Inherited Members

What you'll learn: How access modifiers determine which inherited members a subclass can actually see and use.


Not All Inherited Members Are Visible

When a class inherits from a superclass, Java doesn't simply hand over everything. The access modifier on each superclass member controls whether the subclass can directly access it.

Think of inheritance like moving into a family home: you inherit the house, but some rooms might be locked (private), some open only to family (protected), and some open to everyone (public).


The Visibility Rules

Here's what a subclass can access from its superclass:

  • public members: Always visible. Any subclass, anywhere, can access them.
  • protected members: Visible to subclasses (even in different packages) and to classes in the same package.
  • Package-private (default) members: Visible only if the subclass is in the same package as the superclass.
  • private members: Never visible to subclasses. These belong exclusively to the superclass itself.

Even though private fields technically exist in memory when you create a subclass object, your subclass code cannot directly reference them—they remain hidden behind the superclass's encapsulation wall.


Practical Impact

If you inherit a class with a private field, you'll need to use inherited public or protected getters/setters to interact with it. This respects the original class's encapsulation while still allowing controlled access.

Protected members strike a balance: they're hidden from the outside world but available to specialized subclasses that extend the functionality.


Key Takeaway:
Inheritance passes down members, but only public, protected, and package-private members are visible to subclasses—private members remain hidden and inaccessible.