What is Encapsulation?
Encapsulation means keeping an object's data and related behavior together while controlling how outside code can interact with that data.
Short definition:
Encapsulation protects object state behind a safe public interface.
Two Parts of Encapsulation
1. Bundling
Data and functions belong together inside a class.
class BankAccount {
private:
double balance;
public:
void deposit(double amount);
bool withdraw(double amount);
};
2. Controlled Access
Outside code cannot directly change private data.
Instead, it must use public methods.
account.deposit(500);
account.withdraw(200);
Why Direct Access Is Dangerous
If balance were public:
account.balance = -10000;
The object could enter an invalid state.
With encapsulation, the class can reject invalid actions.
Invariant
An invariant is a rule that should always remain true for an object.
For BankAccount:
balance should not become negative
Encapsulation helps protect invariants.
Encapsulation Is More Than Private Data
Private data alone is not enough.
Bad setter:
void setBalance(double value) {
balance = value;
}
This still allows invalid state.
Better behavior:
bool withdraw(double amount) {
if (amount <= 0 || amount > balance) {
return false;
}
balance -= amount;
return true;
}
Viva Answer
Encapsulation is the OOP principle of binding data and methods inside a class while restricting direct access to internal state. Outside code uses public methods, and those methods protect object invariants.
Quick Check
- What is encapsulation?
- What is an invariant?
- Why is public data risky?
- Is private data alone enough for good encapsulation?