Lesson 8: Encapsulation & Access Modifiers

09 Jul 2026 1 min Swarnil Singhai

Encapsulation hides internal state behind methods so a class can enforce its own rules — no external code can put it in a bad state.

Real-time example

A BankAccount class never lets balance go negative because the field is private and only withdraw() can touch it.

class BankAccount {
    private double balance;

    public void deposit(double amt) { balance += amt; }
    public boolean withdraw(double amt) {
        if (amt > balance) return false;
        balance -= amt;
        return true;
    }
    public double getBalance() { return balance; }
}

What's happening

Because balance is private, the only way to change it is through deposit/withdraw — the invariant (never negative) is guaranteed.

If a field can be set to an invalid value from outside the class, it isn't really encapsulated yet.

Advertisement