Encapsulation
ELI5 — The Vibe Check
Encapsulation is bundling data and the methods that operate on it into one unit, and hiding the internal state from the outside world. It's like a capsule pill — the medicine is inside and you interact with the coating, not the guts. Private fields and public methods in action.
Real Talk
Encapsulation is an OOP principle where an object's internal state is hidden from the outside world. External code interacts only through a defined public interface (methods). This protects invariants, reduces coupling, and allows internal implementation to change without affecting consumers.
Show Me The Code
class BankAccount {
private balance: number = 0;
deposit(amount: number) {
if (amount > 0) this.balance += amount;
}
getBalance(): number {
return this.balance; // controlled access
}
}
When You'll Hear This
"Encapsulation protects the balance from being set directly." / "Use encapsulation to enforce invariants within the class."
Related Terms
Abstraction
Abstraction is hiding the messy details and showing only what matters.
Inheritance
Inheritance lets a class take on all the properties and behaviors of another class.
Polymorphism
Polymorphism means the same method call can do different things depending on which object it's called on. Call 'speak()' on a Dog and you get a bark.
Single Responsibility
Single Responsibility means every class or function should do ONE thing and do it well.