Skip to content
BENIBIX Learn

Encapsulation

Development🧭 Programming ParadigmsObject-Oriented Programming

Also known as Data Hiding, Information Hiding

Hiding an object's data. Other code must use safe methods to change it.

Think of it like

Think of it like a piggy bank. You can put coins in the slot, but you cannot reach in and grab them.

Example

Emma's Account class hides its balance. Other code must call deposit(), which says no to amounts below zero.

Why it matters

It stops other code from breaking an object by mistake.

Definition

Encapsulation means keeping an object's data inside it. Other code can only change it through the object's own methods. The data is hidden, and only safe doors are left open. That way the object can check every change, like saying no to a negative balance. Code outside does not need to know how the object stores things. So the inside can change later without breaking the rest.

Example code

javascript
class Account {
  #balance = 0;
  deposit(n) { this.#balance += n; }
  get balance() { return this.#balance; }
}
The # makes balance private. Only deposit can change it.

Common mistake

Adding a get and a set method for every hidden value. That opens the same door you meant to close.

Key takeaways

  1. 1
    Data stays inside. Hidden from outside code.
  2. 2
    Safe doors only. Methods check each change.
  3. 3
    Free to change inside. Outside code does not break.

Compare