What are the four access levels in Java and who can see each one?
private is visible only inside the class. Default (no keyword) adds the same package. protected adds subclasses in other packages. public is visible everywhere.
Explain it simply
Think of a house. private is your own locked cupboard. Default is the living room, open to everyone in your family (the package). protected is the living room plus relatives who inherit the house (subclasses elsewhere). public is the front gate, open to anyone.
Example
package bank;
public class Account {
private double balance; // only Account
int branchCode; // classes in package bank
protected String holder; // package bank + subclasses anywhere
public String bankName; // everyone
}| Modifier | Same class | Same package | Subclass elsewhere | Everywhere |
|---|---|---|---|---|
| private | yes | no | no | no |
| default | yes | yes | no | no |
| protected | yes | yes | yes | no |
| public | yes | yes | yes | yes |
What to say in the interview
"I start with the tightest access that works: private for fields and helper methods, public only for the intended API. Default access is package-private, and the word default is not written. protected allows subclasses in other packages, but only through inheritance, not through a plain object reference of the parent type. Top-level classes can only be public or package-private."
Common mistakes
- Thinking protected means subclass-only. It also gives access to the whole package.
- Making fields public and giving up control over them.