Video in progress

What is encapsulation and why do we make fields private?

Encapsulation means the state of an object can't be changed directly from outside: the state is touched only through the object's own methods. A private field protects the class invariants (for example, that a balance can't go negative).

📖 Answer

If a field is public, anyone can write any value into it:

account.balance = -1_000_000; // nothing stops this

The encapsulated version:

public class Account {
    private long balance;

    public void withdraw(long amount) {
        if (amount <= 0) throw new IllegalArgumentException("Summa musbat bo'lishi kerak");
        if (amount > balance) throw new IllegalStateException("Mablag' yetarli emas");
        balance -= amount;
    }

    public long getBalance() { return balance; }
}

Now the rules live in one place. If a requirement comes tomorrow that "every withdrawal must write an audit log", you change only withdraw, and the callers never know.

Another benefit: you can freely swap the internal structure. If you replace long balance with BigDecimal, the external API doesn't break.