OOP Fundamentals • EncapsulationEasy⏱️ ~2 min

What is Encapsulation?

Definition
Encapsulation is the OOP principle of bundling data (attributes) and methods that operate on that data within a single unit (class), while restricting direct access to internal state through access modifiers.

Core Concepts:

First, Data Hiding: Internal state is hidden from external access using private/protected access modifiers. External code cannot directly manipulate object internals.

Second, Controlled Access: Public methods (getters/setters) provide controlled access to private data, allowing validation and maintaining invariants.

Third, Information Hiding: Implementation details are hidden behind a public interface. Clients depend on behavior, not internal structure.

Why Encapsulation Matters:
Problem Without Encapsulation: If a BankAccount class exposes balance as public, any code can set account.balance = -5000, violating business rules. Changes to internal representation (switching from single balance to multiple currency balances) break all client code.
Solution With Encapsulation: balance is private. Public method withdraw(amount) validates amount, checks sufficient funds, and updates balance. Internal representation can change without affecting clients.
Interview Tip: Encapsulation is about protecting invariants and enabling change. Always explain the business rule or constraint you're protecting.
💡 Key Takeaways
✓Encapsulation bundles data and methods while hiding internal state
✓Data hiding uses access modifiers to prevent direct access to attributes
✓Controlled access through public methods maintains object invariants
✓Enables changing implementation without breaking client code
✓Fundamental to maintainability and reducing coupling
📌 Interview Tips
1BankAccount hiding balance and providing deposit/withdraw methods
2Person class with private age field and validation in setAge()
3Library system where BookCopy availability is computed, not directly set
← Back to Encapsulation Overview
What is Encapsulation? | Encapsulation - System Overflow