✅ 1. Encapsulation
Definition:
Encapsulation is the practice of hiding internal state and requiring all interaction to be performed through an object’s methods.
Goal:
Protect the internal state of the object from unintended or harmful modifications — data hiding.
How:
- Use
privatefields. - Expose
public/protectedgetter/setter or methods for controlled access. - Prevent direct access to internal data structures.
Example:
public class BankAccount {
private double balance; // encapsulated
public void deposit(double amount) {
if (amount > 0) this.balance += amount;
}
public double getBalance() {
return this.balance;
}
}
You can’t directly modify balance, only via methods that enforce business rules. That's encapsulation.
✅ 2. Abstraction
Definition:
Abstraction is the process of hiding complexity by exposing only the relevant details of an object or system.
Goal:
Reduce complexity for the user of the system. Focus on what an object does, not how it does it.
How:
- Use interfaces or abstract classes.
- Model real-world behaviors with only necessary details.
Example:
public interface PaymentProcessor {
void processPayment(double amount);
}
public class StripePaymentProcessor implements PaymentProcessor {
public void processPayment(double amount) {
// Stripe-specific API integration
}
}
Client code doesn’t care how payment is processed, just that processPayment() is available. That's abstraction.
🔍 Key Differences Table
| Aspect | Encapsulation | Abstraction |
|---|---|---|
| Purpose | Hide internal data and enforce rules | Hide implementation complexity |
| Focus | How data is accessed/modified | What operations are exposed to the user |
| Implemented using | Access modifiers (private, public, etc.) |
Interfaces, abstract classes, polymorphism |
| Goal | Data protection | Simplify usage |
| Example | Private fields with getters/setters | Interface hiding implementation |
🧠 Analogy
- Encapsulation: Think of a capsule — it wraps the medicine (data) inside a shell (methods). You don’t access the content directly.
- Abstraction: Think of a car. You drive using the steering wheel and pedals (interface) without knowing how the engine or transmission works (implementation).
Top comments (0)