protected Members: Package Plus Subclass Access
What you'll learn: How protected combines package-private visibility with special access for subclasses, even outside the package.
The Core Idea
The protected modifier creates a middle ground between package-private and public. A protected member is accessible in two distinct ways:
- Within the same package (just like package-private)
- By subclasses in any package (the extra privilege)
Think of protected like a family secret: anyone in your household (package) knows it, plus your children who've moved to other towns (subclasses in other packages) also have access.
How It Works
When you mark a field or method as protected, classes in the same package can access it directly. Additionally, any class that extends yours—regardless of what package it's in—can access that member through inheritance.
// In package animals
package animals;
public class Animal {
protected String species; // Protected field
protected void makeSound() { // Protected method
System.out.println("Some sound");
}
}
// In the SAME package
package animals;
public class Zoo {
void test() {
Animal a = new Animal();
a.species = "Lion"; // OK: same package
a.makeSound(); // OK: same package
}
}
// In a DIFFERENT package
package pets;
import animals.Animal;
public class Dog extends Animal { // Subclass in different package
void bark() {
this.species = "Canine"; // OK: inherited protected member
this.makeSound(); // OK: inherited protected member
}
}
When to Use protected
Use protected when you want to allow subclasses to access implementation details for customization, while keeping those details hidden from unrelated classes.
Key Takeaway: protected grants access to all classes in the same package PLUS all subclasses anywhere—it's package-private with an inheritance bonus.