Encapsulation

Why can't you touch the internal circuits of a TV? Discover Encapsulation, the pillar of OOP that protects your data from a chaotic world.

April 14, 20264 min read1 / 14

In our last post, we explored Abstraction: the art of representing systems as Ideas. But an Idea without protection is vulnerable. In the messy world of software, you need a way to ensure that your "Ideas" aren't broken by outside code.

This is where the first pillar of OOP comes in: Encapsulation.

The Essentials

The "Safety First" guide to this post:

  1. Data Protection: Encapsulation hides internal data and only allows access through controlled "gates" (methods).
  2. The TV Analogy: You interact via a remote (Public), but you cannot touch the high-voltage circuits inside (Private).
  3. Control: The class creator decides exactly what can be changed and by whom.
  4. Access Modifiers: Keywords like public and private are the tools we use to build these walls.

The Medicine Analogy: Why "Capsule"?

Think about a medical capsule. When you are sick, you take a pill that contains medicine inside a shell.

  1. It Groups Things: The shell holds different chemical powders together in one unit.
  2. It Protects the Contents: The shell prevents the outside environment from damaging the medicine.
  3. It Controls the Release: The shell is designed to dissolve only when it reaches your stomach.

Encapsulation in code does the exact same thing. It groups your data (Attributes) and actions (Behaviors) into a single "capsule" (the Class) and protects them from unintended outside access.

Encapsulation in Action: The Safety Problem

Exposed Data

Data is public. Any code can reach in and set a Student's score to 99,999% or -50%. The system is unstable.

class Student {
  public psp: number;
}

s.psp = -500; // Oops!
// Data is corrupted.

There are no "gates." Anyone can break your logic from the outside.

The Capsule

Data is private. The only way to change it is through a public method that includes validation logic.

class Student {
  private psp: number;
  setScore(s) {
    if (s > 0) this.psp = s;
  }
}

The class controls its own state. Data is protected and always valid.

Code Implementation: Building the Shell

Here is how you protect your sensitive data using access modifiers and setter methods:

class BankAccount { // Hidden attributes (The internal circuits) private balance: number = 0; // Public gateway (The remote control) public deposit(amount: number) { if (amount > 0) { this.balance += amount; console.log(`Deposited ${amount}. New balance: ${this.balance}`); } } public getBalance(): number { return this.balance; } } const account = new BankAccount(); account.deposit(100); // console.log(account.balance); // Error: balance is private!

The Tools of the Trade: Access Modifiers

In languages like Java, we have four main levels of protection. Think of them as security clearances:

  1. Private (The Personal Room): Only the parent class can see.
  2. Default (The Apartment Building): Everyone in the same package (folder) can see.
  3. Protected (The Family Circle): Children can see, even in different folders.
  4. Public (The Town Square): Everyone can see.

Next, we'll see how these "Blueprints" actually come to life in the computer's memory.

Practice what you just read.

Quiz: Encapsulation & TV AnalogyLab: Safe Bank Account
2 exercises