Encapsulation & Access Control
Hide internal state with private fields and expose safe, validated public methods to protect object invariants.
What you'll learn
- Explain why exposing raw mutable fields leads to bugs
- Use private fields and public methods to enforce invariants
- Provide controlled read access with getters
Encapsulation means bundling an object’s data with the methods that operate on it, and restricting direct outside access to internal state.
Why Protect Internal State?
If a BankAccount exposes account.balance publicly, any caller could set account.balance = -5000. By making #balance private (or private double balance in Java/C#/C++), all changes must go through deposit() and withdraw(), where validation rules always run.
Fill-in-the-Blank Exercise
Private State & Getter
Hide balance as a private field (#balance) and expose it read-only via a getter.
class Wallet {
balance = 0;
deposit(amount) {
if (amount > 0) this.#balance += amount;
}
balance() {
return this.#balance;
}
}Try It Yourself (Live OOP Playground)
No console output yet. Try calling console.log(...) in JS.
Check Your Understanding
1. What is the primary benefit of encapsulation?
Finished this lesson?
Your progress is saved locally in your browser, no account needed.