What is the difference between abstraction and encapsulation?
Abstraction decides what to show: it exposes a simple view and hides complexity. Encapsulation decides how to protect: it bundles data with methods and restricts access to it.
Explain it simply
A car's steering wheel and pedals are abstraction: you say "turn" and "go faster" without knowing about the engine. The sealed engine bay with a bonnet lock is encapsulation: parts are enclosed and guarded so they are not tampered with.
Abstraction works at the design level (which operations make sense). Encapsulation works at the implementation level (how state is held and guarded). They support each other.
Example
interface UpiPayment { // abstraction: what you can do
boolean pay(String vpa, int rupees);
}
class BankUpi implements UpiPayment {
private int dailyLimit = 100000; // encapsulation: guarded detail
private int spentToday = 0;
public boolean pay(String vpa, int rupees) {
if (spentToday + rupees > dailyLimit) return false;
spentToday += rupees;
return true;
}
}Callers see only pay. The limit logic is hidden by private.
What to say in the interview
"Abstraction hides complexity by exposing only essential operations, typically through interfaces and abstract classes. Encapsulation hides internal state by making it private and controlling access through methods. One is about the design of the interface, the other about protecting the implementation."
Common mistakes
- Saying they are the same thing with different names.