Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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-private

Examples

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:

100

Accessing 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:

ModifierClassPackageSubclassesEverywhere
privateyesnonono
no modifieryesyesnono
protectedyesyesyesno
publicyesyesyesyes

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.

Thanks for reading!

Donate to the site — we work hard for you.