Encapsulation in Java Explained
Fast recall
Quick revision
Core answer
deposit() or rename() instead. This prevents uncontrolled changes and lets implementation details evolve without forcing callers to change.Whether you understand encapsulation as controlling state through behavior, not just the mechanical habit of generating getters and setters.
Saying encapsulation 'is getters and setters'. A public field with a pass-through getter/setter that does no validation is not encapsulation — it is the same exposure with extra typing.
Show that the real win is isolating change: callers depend on withdraw(), so you can switch balance from double to BigDecimal or add an audit log without touching a single caller.
Interview-ready guide
Interview answer
The cleanest way to frame it is a bank account. If the balance field were public, any line in the whole program could set it to minus fifty thousand and corrupt the account, with nothing to stop it. So you make the field `private` — invisible from outside — and force every change through a method like withdraw, where the rules live once: amount positive, funds sufficient. Those checks then run on every call.
What I'd stress is that encapsulation is about behavior, not setters. You don't add setBalance; you offer deposit and withdraw, because the name states the intent and the method enforces the rule. A setter that just copies its argument is no safer than a public field. I'd watch getters too — returning the live internal list lets a caller mutate your state, so hand back a copy.
The real payoff is that the rules live in one place, and because callers only ever touch the methods, I can switch balance from double to BigDecimal later, or add an audit log, without breaking a single caller.
Encapsulation in Java Explained
Direct Answer
Encapsulation keeps an object's representation behind methods that preserve its rules. Fields are usually private, but the public API does not need a getter and setter for every field: it may expose operations such as deposit() or rename() instead. This prevents uncontrolled changes and lets implementation details evolve without forcing callers to change.
Code Example
public class BankAccount {
private double balance; // hidden — nothing outside can touch it directly
public BankAccount(double initialBalance) {
if (initialBalance < 0)
throw new IllegalArgumentException("Initial balance cannot be negative");
this.balance = initialBalance;
}
// Getter: read-only access from outside
public double getBalance() {
return balance;
}
// Behavior method: encodes the business rule
public void deposit(double amount) {
if (amount <= 0)
throw new IllegalArgumentException("Deposit amount must be positive");
balance += amount;
}
public void withdraw(double amount) {
if (amount <= 0)
throw new IllegalArgumentException("Withdrawal amount must be positive");
if (amount > balance)
throw new IllegalStateException("Insufficient funds");
balance -= amount; // rule checked in ONE place, every time
}
}
// How callers use it:
BankAccount account = new BankAccount(500.0);
account.deposit(200.0);
account.withdraw(100.0);
System.out.println(account.getBalance()); // 600.0
// account.balance = -500; <-- COMPILE ERROR: balance is private
Switch balance from double to BigDecimal later and not a single caller changes — they all use getBalance(), deposit(), and withdraw().
Common Mistakes & Pitfalls
- Calling getters and setters 'encapsulation' — a
privatefield with a pass-through setter that does no checking is the same exposure as a public field, just with more code. - Adding a setter for every field by reflex — exposing
setBalance()lets callers bypass your business rules; expose behavior likedeposit()andwithdraw()instead. - Returning a mutable field straight from a getter — handing back the live
ListorDatelets the caller mutate your private state with.add(); return a copy or an unmodifiable view. - Validating in the constructor but not in the methods — if
withdraw()skips a check the constructor enforces, the object drifts into an invalid state after it is created.
Check your understanding
Answer these without looking back at the article.
- What is the JavaBeans convention in Java?
- How does encapsulation help with maintenance and refactoring?
- What is the difference between encapsulation and abstraction?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.