How does protected access work in Java, and what does it let a subclass do that package-private access does not?
Protected means that the member is open to the class itself, to the classes in the same package, and to any subclass wherever that subclass happens to be.
public class Main {
public static void main(String[] args) {
Base b = new Base();
System.out.println(b.describe());
}
}
And here is the class with a protected member.
public class Base {
protected final String name;
public Base(String name) {
this.name = name;
}
public String describe() {
return "base " + name;
}
}
So what does protected let a subclass do that package-private does not? It lets the subclass reach the member even when the subclass is in a different package.
the level the same class the same package a subclass
elsewhere
----------------- -------------- ---------------- ---------------
public yes yes yes
protected yes yes yes
package-private yes yes no
private yes no no
And here is a subclass in another package that uses the protected member.
package com.example.audit;
import com.example.bank.Base;
public class Auditor extends Base {
public Auditor(String name) {
super(name);
}
public String audit() {
// This works, because name is protected.
return "auditing " + name;
}
}
And there is one detail about that which catches people out. The subclass can reach the protected member through its own object, but not through a reference to the parent type.
public class Auditor extends Base {
public String readName(Base other) {
// This does not compile. other is a Base and not an
// Auditor, so the protected access does not apply.
return other.name;
}
}
And there is one more detail worth knowing about, and it is that the rule for the package is the opposite of what people expect. A protected member is visible to every class in the same package, whether or not it extends the class. So protected is not only about subclasses, it is package access plus the subclass rule.
And there is a third thing that is worth knowing about, and it is about the reason for the rule. The rule exists so that a subclass can work with the state that its parent owns, even when the subclass lives in another package. It is a deliberate exception to the normal rule that everything private is hidden.
So the rule to remember is this. Protected is package access plus the right for a subclass to reach the member on its own object.
The last question in this topic is about why protected fields are a bad idea.