Students often mix up encapsulation and abstraction. Explain the difference clearly and illustrate both using a single real-world class, such as a bank account.
Show hints
One is about what you show; the other is about how you protect it.
Show the explanation
Model answer. Both involve hiding something, but they hide different things for different reasons.
Abstraction — hiding complexity, showing only what matters
- Focuses on what an object does, not how.
- Achieved through interfaces, abstract classes and well-chosen public methods.
- It is a design-level idea: deciding which operations the outside world needs.
Encapsulation — bundling data with the code that guards it
- Keeps an object's fields and the methods that operate on them together, and restricts direct access to the fields (usually
private). - Ensures the object's internal state can only change through controlled paths that enforce rules (invariants).
- It is an implementation-level mechanism.
Bank account example
public class BankAccount {
private double balance; // encapsulated state
public void deposit(double amount) {
if (amount <= 0) throw new IllegalArgumentException("Amount must be positive");
balance += amount;
}
public void withdraw(double amount) {
if (amount > balance) throw new IllegalStateException("Insufficient funds");
balance -= amount;
}
public double getBalance() { return balance; }
}- Abstraction: a caller sees just
deposit,withdrawandgetBalance. It does not know about transaction logs, fraud checks or which database stores the balance. - Encapsulation:
balanceis private, so no code can writeaccount.balance = -5000. Every change goes through methods that enforce "no negative deposits" and "no overdraft".
One-line summary: abstraction decides what to expose; encapsulation decides how to protect the rest.
Common mistake: believing that making every field private and adding a public getter and setter for each one is encapsulation. A setter like setBalance(double b) with no checks exposes the field just as much as making it public. Good encapsulation exposes meaningful behaviour (withdraw) rather than raw data. An interviewer may follow up by asking how you would make the class thread-safe — the answer builds on encapsulation, because all state changes pass through a few methods you can synchronise.
Original UniCircle question. Last reviewed 28 Oct 2026.
