Course contentsShow
← Java
Lesson 707 of 2,87017. Access Control in DepthFree lesson

Protected Access Without Inheritance

Discover that protected members are accessible to any class in the same package, not just subclasses.

Protected Access Without Inheritance

What you'll learn: You'll discover that protected members aren't only for subclasses—they're also accessible to any class in the same package, even without inheritance.

The Surprising Package-Level Access

Most developers think of protected as "subclass-only" access, but that's only half the story. The protected modifier actually grants access to two groups:

  1. Subclasses (even in different packages)
  2. Any class in the same package (regardless of inheritance relationship)

This second point often surprises beginners. If two classes live in the same package, one can access the other's protected members without extending it.

Why This Matters

Think of a package as a "trust boundary." Java assumes classes in the same package are closely related and designed to work together. The protected modifier respects this relationship by granting package-level access automatically.

package animals;

public class Dog {
    protected void bark() {
        System.out.println("Woof!");
    }
}
package animals;

public class DogTrainer {  // Not a subclass of Dog!
    public void trainDog(Dog dog) {
        dog.bark();  // Legal! Same package, protected access granted
    }
}

Notice DogTrainer doesn't extend Dog, yet it can call the protected method bark() because both classes share the animals package.

The Analogy

Think of protected like a neighborhood clubhouse key. You get in if:

  • You're family (subclass), or
  • You live on the same street (same package)

Key Takeaway: Protected members are accessible to all classes in the same package, not just subclasses—making protected more permissive within a package than many beginners expect.