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

Inheriting Protected Members Across Packages

Accessing protected inherited members from a subclass in a different package; direct access vs reference type restrictions.

Inheriting Protected Members Across Packages

What you'll learn: How subclasses in different packages can access protected inherited members, and the important restrictions based on reference types.

When a subclass inherits protected members from a superclass in a different package, Java allows direct access to those members—but only through the subclass's own type or its subtypes, not through arbitrary superclass references.

Direct Access in the Subclass

Inside your subclass methods, you can directly use inherited protected members as if they were your own. You can access them on this, on other instances of your subclass type, or on instances of your subclass's subclasses.

// In package animals
public class Animal {
    protected String species;
    protected void makeSound() { }
}

// In package pets
import animals.Animal;

public class Dog extends Animal {
    public void example() {
        // ✓ Direct access on 'this'
        this.species = "Canine";
        makeSound();
        
        // ✓ Access through another Dog reference
        Dog otherDog = new Dog();
        otherDog.species = "Canine";
        otherDog.makeSound();
    }
}

The Reference Type Restriction

You cannot access protected members through a reference of the superclass type, even though inheritance exists:

public void restricted() {
    Animal animal = new Dog();
    animal.species = "Canine";  // ✗ Compile error!
    animal.makeSound();          // ✗ Compile error!
}

Why? Java enforces that protected cross-package access happens "through inheritance," meaning you must use your own class's inherited copy, not reach across to touch the superclass reference's protected state.

Key Takeaway: Subclasses in different packages can access inherited protected members directly (on this or through their own subclass references), but not through superclass-typed references—Java restricts protected access to the inheritance hierarchy you own.