Skip to content
AgileLogics
4 min read

Access Modifiers

Prerequisites: Instance vs. static members

Access modifiers control which other code can see a field, method, or class:

  • public — visible everywhere.
  • private — visible only inside the same class.
  • protected — visible to the same package and to subclasses.
  • (none, "package-private") — visible only within the same package.
class BankAccount {
    private double balance;

    public double getBalance() {
        return balance;
    }

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

Making balance private and exposing it only through getBalance() and deposit() means the class can enforce rules (like rejecting a negative deposit) — this pattern is called encapsulation.

Common mistakes

  • Making every field public "to keep things simple" — this removes any ability to validate changes, and any other class can then set balance directly to an invalid value.