Memra

Access modifiers & encapsulation

public, protected, package-private, private — and why private fields with getters matter.

Controlling visibility

Java has four access levels, from broadest to narrowest:

| Modifier | Same class | Same package | Subclass (any pkg) | Any class | |---|---|---|---|---| | public | yes | yes | yes | yes | | protected | yes | yes | yes | no | | *(none — package-private)* | yes | yes | no | no | | private | yes | no | no | no |

A member with no modifier is package-private (also called "default" access) — accessible within the same package only.

Encapsulation hides implementation details: make fields private and expose controlled access through public getters and setters:

public class BankAccount {
    private double balance;

    public double getBalance() { return balance; }

    public void deposit(double amount) {
        if (amount > 0) balance += amount;
    }
}

Benefits: the class can validate changes, change its internal representation later without breaking callers, and centralise logging or events.

NORMAL ~/memra/learn/java-from-zero/access-modifiers-encapsulation utf-8 LF