What is the difference between encapsulation and abstraction in Java?
Abstraction hides complexity by showing only what a user needs, usually through interfaces or abstract classes. Encapsulation hides data by keeping fields private and exposing controlled methods. One is about design, the other about protection.
Explain it simply
A scooter has a throttle and brake (abstraction: you do not need to know the engine). The fuel tank is sealed and you cannot pour petrol straight into the carburettor (encapsulation: access is controlled). Abstraction answers "what can I do?". Encapsulation answers "who may touch the inside?".
Example
interface UpiPayment { // abstraction: only the what
boolean pay(String toUpiId, double amount);
}
class PhonePeStyle implements UpiPayment {
private double walletBalance = 500; // encapsulation: hidden state
public boolean pay(String toUpiId, double amount) {
if (amount <= 0 || amount > walletBalance) return false;
walletBalance -= amount; // only changed through rules
return true;
}
}What to say in the interview
"Abstraction is achieved with interfaces and abstract classes, and it lets callers depend on a contract rather than an implementation. Encapsulation is achieved with private fields and public methods, and it protects the object's invariants, for example a balance can never go negative. They work together, but abstraction hides complexity at the design level while encapsulation hides data at the implementation level."
Common mistakes
- Giving the same definition for both.
- Writing a private field with a public setter that does no checking, which defeats encapsulation.