Memra

Access modifiers & encapsulation

◈ 4 cards

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

Controlling visibility

Java has four access levels, from broadest to narrowest:

ModifierSame classSame packageSubclass (any pkg)Any class
publicyesyesyesyes
protectedyesyesyesno
(none — package-private)yesyesnono
privateyesnonono

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.

publicany class, any packageprotectedadds subclasses in other packagesno modifiersame package onlyprivatesame class only
Each level is a strict superset of the next: protected is package-private plus subclasses in other packages, which is exactly why protected is the wider of the two.
NORMAL ~/memra/learn/java-from-zero/access-modifiers-encapsulation utf-8 LF