Encapsulation is one of the four main pillars of Object-Oriented Programming (OOP).
It refers to wrapping the data (variables) and the code (methods) that works on the data into a single unit- a class.
But most importantly, it restricts direct access to internal data using access modifiers (like private, public, etc.).
🧠 Think of it like...
A capsule or medicine bottle:
The medicine (data) is hidden inside
You access it only through a prescription (methods)
🔸 Example Without Encapsulation:
class Account {
public int balance; // not secure
void displayBalance() {
System.out.println("Balance: " + balance);
}
}
public class Main {
public static void main(String[] args) {
Account acc = new Account();
acc.balance = -5000; // anyone can assign wrong value!
acc.displayBalance();
}
}This is bad practice because:
balancecan be changed directlyNegative or invalid values can be assigned
No control over how data is used
🔒 Proper Encapsulation (Best Practice)
class Account {
private int balance = 0; // data hidden
public void setBalance(int amount) {
if (amount >= 0) {
balance = amount;
} else {
System.out.println("Invalid balance.");
}
}
public int getBalance() {
return balance;
}
}
public class Main {
public static void main(String[] args) {
Account acc = new Account();
acc.setBalance(5000); // safe
System.out.println("Balance: " + acc.getBalance());
}
}Balance: 5000🔒 Why Encapsulation Is Important
Benefit | Description |
|---|---|
Data Protection | Prevents unauthorized access or misuse |
Validation | You can add checks in |
Readability & Maintenance | Easier to manage and debug, logic is centralized |
Modularity | You can update internal code without affecting external classes |
Loose Coupling | Other classes interact only via method interfaces, not directly with fields |
🔓 Access Modifiers Recap
Modifier | Access Level |
|---|---|
| Only within the same class |
| Accessible from anywhere |
| Within same package & subclasses |
(default) | Within same package only |
In encapsulation, we typically use:
privatefor variablespublicfor getter/setter methods