What are access modifiers?
Solution and explanation
What they are
Access modifiers control where a class, constructor, method or field can be used from. They are Java's main tool for encapsulation: hide internal details, expose only what callers need.
The four levels
| Modifier | Same class | Same package | Subclass (other package) | Everywhere |
|---|---|---|---|---|
| private | Yes | No | No | No |
| (none) package-private | Yes | Yes | No | No |
| protected | Yes | Yes | Yes (through inheritance) | No |
| public | Yes | Yes | Yes | Yes |
Example
package com.portal.payment;
public class PaymentService { // usable everywhere
private String apiKey; // only inside this class
int retryCount = 3; // package-private: classes in com.portal.payment
protected void log(String msg) { } // package + subclasses anywhere
public boolean pay(double amount) { // public API
return charge(amount);
}
private boolean charge(double amount) { return true; } // implementation detail
}
Where each can be used
- Top-level classes: only public or package-private.
- Members (fields, methods, constructors, nested classes): all four.
- Interface methods are public by default; interface fields are
public static final.
Java 9 modules
With JPMS, even public classes are visible to other modules only if their package is exported in module-info.java, which adds a layer above these modifiers.
Rule of thumb: make everything as private as possible, and widen access only when there is a reason.
