public / protected / private
Access modifiers control where a class, field, method or constructor is visible from.
Available since: Java 1.0
Syntax
public | protected | private | (no modifier) — package-privateExamples
Typical encapsulation: the field is private, and it is used through public methods:
class Account {
private int balance;
public void deposit(int amount) {
if (amount <= 0) {
throw new IllegalArgumentException("amount must be positive");
}
balance += amount;
}
public int getBalance() {
return balance;
}
}
void main() {
Account account = new Account();
account.deposit(100);
IO.println(account.getBalance());
}Output:
100Accessing a private field from another top-level class does not compile:
// src/Shop.java
public class Shop {
void pay(Account account) {
account.balance = 1_000_000; // error: balance has private access in Account
}
}Notes
Visibility from narrowest to widest:
| Modifier | Class | Package | Subclasses | Everywhere |
|---|---|---|---|---|
private | yes | no | no | no |
| no modifier | yes | yes | no | no |
protected | yes | yes | yes | no |
public | yes | yes | yes | yes |
Fields are almost always private, and only the needed methods are exposed. A top-level class can only be public or have no modifier, and a public class must live in a file with its own name. In a compact source file all classes are nested in one implicit class, so private does not apply between them — check access with ordinary files.
See also
- import / package — package sets the file's package, import lets you use short names of classes from other packages.
- class — Declares a class — a description of objects: their fields and methods.
- extends — Declares inheritance: the class gets the parent's fields and methods.
- static — Makes a field or method belong to the class itself rather than to each object.
In the tutorial
- Packages and access modifiers — Packages and import in Java, the public, protected and private modifiers and default access, building and running a multi-file project.