Beginner
Encapsulation
📂 Phase 3: Object-Oriented Programming (Days 11–16) · JavaEncapsulation means bundling data (fields) and the methods that operate on that data into a single unit (a class), while restricting direct access to the internal state from outside that class.
The Problem Encapsulation Solves
// WITHOUT encapsulation — anyone can set invalid data
public class Account {
public double balance;
}
Account acc = new Account();
acc.balance = -5000; // invalid, but nothing stops it!
Achieving Encapsulation: Private Fields + Public Getters/Setters
public class Account {
private double balance; // hidden from outside access
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
if (balance >= 0) {
this.balance = balance;
} else {
System.out.println("Balance cannot be negative");
}
}
}
Account acc = new Account();
acc.setBalance(-5000); // rejected — prints the warning
acc.setBalance(1000); // accepted
System.out.println(acc.getBalance()); // 1000.0
Access Modifiers Recap
| Modifier | Accessible From |
|---|---|
| private | Only within the same class |
| default (none) | Same package only |
| protected | Same package + subclasses (any package) |
| public | Anywhere |
Why Encapsulation Matters
- Validation: setters can reject invalid values before they're ever stored
- Flexibility: internal implementation can change later without breaking code that uses the getters/setters
- Security: sensitive fields (like passwords or balances) are never exposed directly
Interview tip: A common question is "What's the difference between encapsulation and abstraction?" — Encapsulation is about HIDING data via access control; abstraction is about HIDING implementation complexity by exposing only essential behavior. They work together but solve different problems.