In Java, abstraction and encapsulation are both core Object-Oriented Programming (OOP) concepts, but they serve different purposes.
Abstraction
What it means:
Abstraction is hiding implementation details and showing only essential features.
It focuses on what an object does, not how it does it.
How it’s achieved in Java:
abstractclassesinterfaces
Java Example (Abstraction using interface)
interface Payment {
void pay(double amount); // only method declaration (what to do)
}
class CreditCardPayment implements Payment {
@Override
public void pay(double amount) {
System.out.println("Processing credit card payment of $" + amount);
}
}
public class Main {
public static void main(String[] args) {
Payment payment = new CreditCardPayment();
payment.pay(100);
}
}
Explanation:
The
Paymentinterface defines what should be done (pay()).The implementation details (how payment is processed) are hidden inside
CreditCardPayment.The user of
Paymentdoesn’t need to know how it works internally.
Encapsulation
What it means:
Encapsulation is wrapping data (variables) and methods together and restricting direct access to some of the object’s components.
It focuses on data protection.
How it’s achieved in Java:
privatevariablesPublic
gettersandsetters
Java Example (Encapsulation)
class BankAccount {
private double balance; // hidden data
public double getBalance() {
return balance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
}
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount();
account.deposit(500);
System.out.println(account.getBalance());
}
}
Explanation:
balanceis private → cannot be accessed directly.Access is controlled through
deposit()andgetBalance().This protects the object’s internal state.
Key Differences
| Abstraction | Encapsulation |
|---|---|
| Hides implementation details | Hides internal data |
| Focuses on behavior (what) | Focuses on data protection |
| Achieved using interfaces & abstract classes | Achieved using access modifiers |
| Design-level concept | Implementation-level concept |
Simple Analogy
Abstraction → Driving a car: You use the steering wheel and pedals without knowing how the engine works.
Encapsulation → The car’s engine is hidden under the hood so you can’t directly modify its parts.
Nenhum comentário:
Postar um comentário