Protected Access in Inheritance: The Protected Modifier
What you'll learn: How the protected modifier creates a special middle-ground access level that bridges package-private and public, giving both same-package classes and subclasses (even across packages) visibility to members.
The Protected Sweet Spot
The protected modifier sits between package-private and public access. It grants access to:
- All classes in the same package (just like package-private)
- All subclasses, even in different packages (the inheritance bonus)
Think of protected as a family inheritance pass: close neighbors (same package) can access it, and your descendants (subclasses) inherit the right to access it no matter where they live.
How Protected Works
When you mark a field or method as protected, you're saying: "This is for internal use, but I want my subclasses to be able to access or override it, even if they're in other packages."
package animals;
public class Animal {
protected String species; // Accessible to subclasses
protected void makeSound() {
System.out.println("Some sound");
}
}
package pets;
import animals.Animal;
public class Dog extends Animal {
public void identify() {
species = "Canine"; // OK: subclass accessing protected field
makeSound(); // OK: subclass accessing protected method
}
}
Meanwhile, any class in the animals package can also access species and makeSound() directly, even if they don't extend Animal.
Why Use Protected?
Protected is ideal when you want to hide implementation details from the general public but allow subclasses to customize or access internal behavior. It supports the template method pattern and extensibility while maintaining encapsulation.
Key Takeaway: The protected modifier grants access to both same-package classes and all subclasses (regardless of package), making it the natural choice for members meant to be inherited and customized.