🔐 Encapsulation — “Protect the Data”
➤ What It Is:
Encapsulation means wrapping data (variables) and methods (functions) together into a single unit, typically a class, and restricting direct access to some components using access modifiers (private
, public
, etc.).
🎯 Purpose:
- To hide internal object details from outside interference.
- To ensure control over data using getter and setter methods.
✅ Example:
class BankAccount {
private double balance; // Hidden from outside
public void deposit(double amount) {
if(amount > 0) balance += amount;
}
public void withdraw(double amount) {
if(amount > 0 && amount <= balance) balance -= amount;
}
public double getBalance() {
return balance;
}
}
Here, you can’t access balance
directly, only via controlled methods.
🎭 Abstraction — “Show Only What’s Necessary”
➤ What It Is:
Abstraction means hiding implementation details and only exposing essential features of an object.
You can achieve abstraction in Java using:
- Abstract classes
- Interfaces
🎯 Purpose:
- To focus on what an object does, not how it does it.
- Makes code more modular, extensible, and easier to understand.
✅ Example using Interface:
interface Vehicle {
void start(); // Abstract method
void stop();
}
class Car implements Vehicle {
public void start() {
System.out.println("Car starts with key");
}
public void stop() {
System.out.println("Car stops with brake");
}
}
The user of the Vehicle
interface doesn’t care how the Car
starts or stops—just that it does.
🧠 Side-by-Side Comparison
Feature | Encapsulation | Abstraction |
---|---|---|
Goal | Hide data | Hide complexity |
Focus | How you protect data | How you hide implementation logic |
Accessed via | Getters and Setters | Abstract classes and Interfaces |
Achieved Using | private + public methods | abstract keyword / interfaces |
Hides | Object’s internal state | Implementation complexity |
Used For | Data hiding | Design flexibility |
Example | Banking system with account balance | Interface for all types of vehicles |