Video in progress

Strong Junior 🧱 OOP and SOLID

Who can actually see a `protected` member?

Child classes and all classes in the same package. Most people think it is "only for child classes", but any class in the same package can freely access a protected member.

📖 Answer

The four levels in Java:

Modifier Inside the class Package Child class (other package) Everyone
private yes no no no
(nothing written) yes yes no no
protected yes yes yes no
public yes yes yes yes

So protected is wider than package-private, not narrower.

One more subtle point: a child class in another package can access a protected member only through its own type:

// in the com.app.b package
class Child extends com.app.a.Parent {
    void test(Parent other, Child same) {
        this.secret();   // OK
        same.secret();   // OK
        other.secret();  // compile error: a different Parent object
    }
}

In practice: avoid making fields protected, since that also breaks encapsulation. If a child class needs it, offer a protected method.