Package-Private Members and Subclass Access
What you'll learn: You'll understand that package-private members are only accessible to subclasses when those subclasses are in the same package as the superclass.
The Core Idea
Remember that package-private (default) access means a member is visible to any class in the same package. When inheritance enters the picture, the rule doesn't change—it stays firmly tied to packages, not to inheritance relationships.
If you have a superclass with package-private members and create a subclass in the same package, that subclass can access those package-private members freely. But if you create a subclass in a different package, even though it inherits from the superclass, it cannot access those package-private members.
Why This Matters
This is a crucial distinction from protected access. Package-private access cares only about package boundaries—inheritance doesn't grant any special privileges. It's like a members-only club where membership is determined by your address (package), not your family tree (inheritance).
Simple Illustration
// File: animals/Animal.java
package animals;
public class Animal {
String name; // package-private
}
// File: animals/Dog.java
package animals;
public class Dog extends Animal {
public void printName() {
System.out.println(name); // ✓ Works: same package
}
}
// File: pets/Pet.java
package pets;
import animals.Animal;
public class Pet extends Animal {
public void printName() {
System.out.println(name); // ✗ Error: different package
}
}
Even though Pet is a subclass of Animal, it's in a different package, so it cannot see the package-private name field.
Key Takeaway: Package-private members are accessible in subclasses only if the subclass resides in the same package as the superclass—inheritance alone does not grant access across package boundaries.