Encapsulation is one of the four foundational principles of object-oriented design. It is the practice of grouping data (variables) and behavior (methods) that operate on that data into a single unit (typically a class) and restricting direct access to the internal details of that class.
In simple terms:
Encapsulation = Data hiding + Controlled access
Think of a bank account as a vault inside a bank. You don't get to walk into the vault and change the numbers yourself.
In programming, Encapsulation is typically achieved using:
private
, protected
, public
)It helps you build systems that are robust, secure, and easy to maintain. Here's why it's essential:
In a well-encapsulated design, external code doesn’t need to know how something is done, it only needs to know what can be done.
Let’s look at two practical examples that demonstrate how encapsulation helps you protect internal state, enforce business rules, and expose only what’s necessary.
In a banking system, you want users to deposit and withdraw funds, but you must prevent direct manipulation of the account balance. Here’s how encapsulation helps:
balance
is marked private
, so no external class can access or modify it directly.deposit()
and withdraw()
are public entry points that validate user input before updating the state.getBalance()
allows read-only access, without revealing the underlying variable or letting external code change it.This ensures the account remains in a valid state at all times and business rules are enforced through controlled interfaces.
In this example, a PaymentProcessor
class accepts a card number and amount, but internally masks the card number to protect user privacy. Again, encapsulation allows us to hide implementation details while offering a clean interface.
processPayment()
.This design secures sensitive data and centralizes masking logic in one place, making the system safer and easier to maintain.