Access Modifiers

Four Levels of Access

Access modifiers decide who can see a class, field, constructor or method. From most restrictive to least:

ModifierSame classSame packageSubclass (other package)Everywhere
privateyesnonono
(default, no keyword)yesyesnono
protectedyesyesyesno
publicyesyesyesyes
  • A top-level class can only be public or default (package-private).
  • A .java file can have at most one public top-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.