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.
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:
- Data Protection: Encapsulation hides internal data and only allows access through controlled "gates" (methods).
- The TV Analogy: You interact via a remote (Public), but you cannot touch the high-voltage circuits inside (Private).
- Control: The class creator decides exactly what can be changed and by whom.
- Access Modifiers: Keywords like
publicandprivateare 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.
- It Groups Things: The shell holds different chemical powders together in one unit.
- It Protects the Contents: The shell prevents the outside environment from damaging the medicine.
- 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
Data is public. Any code can reach in and set a Student's score to 99,999% or -50%. The system is unstable.
public psp: number;
}
s.psp = -500; // Oops!
// Data is corrupted.
There are no "gates." Anyone can break your logic from the outside.
Data is private. The only way to change it is through a public method that includes validation logic.
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:
- Private (The Personal Room): Only the parent class can see.
- Default (The Apartment Building): Everyone in the same package (folder) can see.
- Protected (The Family Circle): Children can see, even in different folders.
- 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.