Encapsulation
Encapsulation means protecting internal data and controlling how it can be accessed or changed. A class wraps its data together with the methods that are allowed to touch that data.
- Protect the data
- Allow controlled access
Real World Example: Bank Account
Example: Bank AccountA BankAccount has internal data, its balance. Should any other part of the program be allowed to change it directly?
account.balance = 1000000;
account.balance = -5000;
No. Direct access like this is dangerous, nothing stops the balance from being set to a negative number or an unrealistic value. The balance must stay protected. Instead, the class exposes controlled actions: deposit(), withdraw(), getBalance(). Each method checks the rules (for example, rejecting a negative deposit) before it touches the data.
Encapsulation in Java
Code Exampleclass BankAccount {
private double balance;
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
public void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
}
}
public double getBalance() {
return balance;
}
}
Public vs Private
private: only usable inside the class. Blocks direct access, this is howbalancestays protected.public: usable from outside the class. Gives controlled access, this is howdeposit()andwithdraw()reach the outside world safely.
Class Diagram
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ BankAccount โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ - balance: double โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ + deposit(amount): void โ
โ + withdraw(amount): void โ
โ + getBalance(): double โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
- marks a private member, + marks a public member. balance stays hidden behind the class boundary, only the three public methods can reach it.
Key Idea: Encapsulation = Private Data + Public Methods.
Exam Focus Points
- Encapsulation wraps data and methods together inside one class.
- Private fields block direct outside access; public methods provide controlled access instead.
- A well encapsulated class validates data (for example, rejecting an invalid withdrawal) before changing it.
Summary
- Encapsulation protects an object's internal data from being changed directly.
- Data is kept
private, actions that are safe to expose are keptpublic. - Public methods act as checkpoints, they enforce the rules before the data changes.
- Encapsulation = Private Data + Public Methods.