What is the difference between protected and default (package-private) access in Java?
Default access lets only classes in the same package use the member. Protected allows the same package plus subclasses in any package, but through inheritance.
Explain it simply
Default access is like a society's internal notice: only residents of the same building (package) can see it. Protected is that plus family: a relative (subclass) living in another city (package) may also use it, as a relative.
The order from widest to narrowest is public, protected, default (no keyword), private.
Example
package bank;
public class Account {
protected double balance; // package + subclasses
double branchCode; // package only
}
package bank.partner;
import bank.Account;
public class PartnerAccount extends Account {
void show() {
System.out.println(balance); // ok: inherited
// System.out.println(branchCode); // error: not visible
}
}A subclass in another package reaches protected members only on its own type, not on an arbitrary Account object.
What to say in the interview
"Default (no modifier) is visible within the package only. Protected is visible within the package and to subclasses even in other packages. Protected is wider, and I keep members as narrow as the design allows."
Common mistakes
- Thinking default access is the same as public or that it reaches subclasses in other packages.