# Encapsulation

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

**Field:** Software Development  
**Category:** Programming Paradigms  
**Also known as:** Data Hiding, Information Hiding

## 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.

## 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

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

## 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.

## Why it matters

It stops other code from breaking an object by mistake.

## Common mistake

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

## Three principles

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

## Related terms

- [Object-Oriented Programming (OOP)](https://learn.benibix.com/term/development/object-oriented-programming)
- [Abstraction (Programming)](https://learn.benibix.com/term/development/abstraction)
- [Class](https://learn.benibix.com/term/development/class)
- [Method (Programming)](https://learn.benibix.com/term/development/method)
- [Access Modifier](https://learn.benibix.com/term/development/access-modifier)

## Told apart from

- [Encapsulation vs Abstraction](https://learn.benibix.com/compare/encapsulation-vs-abstraction): Encapsulation and abstraction both hide things, but not the same things. Encapsulation hides an object's data, so only its methods can change it. Abstraction hides how a job is done. You see only a simple way to use it.

---

Source: https://learn.benibix.com/term/development/encapsulation
Author: Behnia Zarei (a developer in Vienna, Austria, who builds and teaches data, AI and business intelligence at BENIBIX)
Publisher: BENIBIX Learn (https://learn.benibix.com/)
Last updated: 2026-11-17
Licence: CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Quote freely with attribution.
