Interview frequency: …
Short answer
The four pillars are encapsulation, abstraction, inheritance, and polymorphism. Encapsulation hides and protects internal state, while abstraction hides complex implementation details and exposes only the necessary interface.
Explanation
Encapsulation combines data and the operations on it in one unit (a class) and restricts direct access to variables except through getters/setters or specific methods, protecting state consistency. Abstraction simplifies the programming view for the user, like pressing a car's start button without needing to understand the combustion cycle.
Code example
class BankAccount {
private balance: number = 0;
public deposit(amount: number): void {
if (amount <= 0) throw new Error('Invalid amount');
this.balance += amount;
}
public getBalance(): number {
return this.balance;
}
}Common mistakes
- Confusing encapsulation with merely writing getters and setters for every field without validation or protection logic.
- Treating abstraction and encapsulation as synonyms, ignoring that one hides data and the other hides complexity.