Careeroza
Access Modifiers
Four Levels of Access
Access modifiers decide who can see a class, field, constructor or method. From most restrictive to least:
| Modifier | Same class | Same package | Subclass (other package) | Everywhere |
|---|---|---|---|---|
private | yes | no | no | no |
| (default, no keyword) | yes | yes | no | no |
protected | yes | yes | yes | no |
public | yes | yes | yes | yes |
- A top-level class can only be
publicor default (package-private). - A
.javafile can have at most onepublictop-level class, and the file name must match it. - Default access is also called package-private.
private in Action
Example
Code outside the class must go through the public method. The private field and the private helper are hidden.
public class Main {
public static void main(String[] args) {
Wallet w = new Wallet();
w.addMoney(500);
w.addMoney(-100);
System.out.println("Balance: " + w.getBalance());
// w.balance = 1000000; // compile error: balance has private access
}
}
class Wallet {
private int balance;
public void addMoney(int amount) {
if (isValid(amount)) {
balance += amount;
System.out.println("Added " + amount);
} else {
System.out.println("Rejected " + amount);
}
}
public int getBalance() {
return balance;
}
private boolean isValid(int amount) {
return amount > 0;
}
}Output
Added 500 Rejected -100 Balance: 500
Choosing a Modifier
Tip: Start with private for every field and helper method. Open things up (protected, public) only when another class really needs them. Smaller public surface = fewer bugs and easier changes later.