What is abstraction?
Solution and explanation
What it is
Abstraction means showing only the essential features of something and hiding the implementation details. The caller knows what an object does, not how it does it.
Analogy: when you drive a car you use the steering, accelerator and brake. You do not need to know about fuel injection or the ABS algorithm. When you pay with UPI you tap "Pay"; the bank-to-bank NPCI messaging is hidden.
Achieved in Java with
- Abstract classes (0–100% abstraction)
- Interfaces (full abstraction of behaviour)
public interface NotificationSender { // WHAT: send a notification
void send(String to, String message);
}
public class EmailSender implements NotificationSender { // HOW: SMTP
public void send(String to, String message) { /* SMTP connection, MIME, retries… */ }
}
public class SmsSender implements NotificationSender { // HOW: SMS gateway API
public void send(String to, String message) { /* HTTP call to gateway */ }
}
public class InterviewScheduler {
private final NotificationSender sender; // depends on the abstraction only
public InterviewScheduler(NotificationSender sender) { this.sender = sender; }
public void schedule(String candidate) {
sender.send(candidate, "Your interview is on Monday 10 AM");
}
}
InterviewScheduler works with email, SMS or WhatsApp senders without changing a line.
Benefits
- Reduces complexity for callers.
- Implementations can change or be swapped (loose coupling).
- Enables testing with fake/mock implementations.
Abstraction vs encapsulation
| Abstraction | Encapsulation |
|---|---|
| Hides complexity (design level) | Hides data (implementation level) |
| Focuses on what an object does | Focuses on how state is protected |
| Interfaces, abstract classes | private fields + public methods |
