Skip to content
Guest
Learn OOP · Course Syllabus Show lessons
Core OOP Foundations · 8 min read · Beginner

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)

Encapsulated BankAccount
Live Result
Console Output

No console output yet. Try calling console.log(...) in JS.

Check Your Understanding

Score: 0 / 1

1. What is the primary benefit of encapsulation?

Study Workspace

Finished this lesson?

Your progress is saved locally in your browser, no account needed.

Search courses, lessons, and references

Type to search across all courses, lessons, and quick references.

Press Esc to close Powered by Pagefind