Is encapsulation the same as data hiding?
Not exactly. Encapsulation bundles data and the methods that work on it into one unit. Data hiding is the part where the fields are made private so outsiders can only use the safe methods.
Explain it simply
A medicine capsule holds powder inside a shell: that bundling is encapsulation. The shell stopping you from touching the powder directly is data hiding. A class bundles fields and methods together (encapsulation) and uses private to keep the fields out of reach (data hiding).
You can bundle without hiding, for example a class with all-public fields. That is encapsulated in the narrow sense but offers no protection. Good encapsulation uses hiding to protect rules, such as "balance never goes negative".
Example
class Wallet {
private int rupees; // hidden
public void add(int amount) { // controlled entry
if (amount <= 0) throw new IllegalArgumentException("amount must be positive");
rupees += amount;
}
public int balance() { return rupees; }
}Outside code cannot write wallet.rupees = -500. It must go through add, which enforces the rule in one place.
What to say in the interview
"Encapsulation is bundling state and behaviour together in a class. Data hiding is restricting direct access to that state, usually with private fields. Hiding is the tool, and keeping the object's rules safe is the purpose."
Common mistakes
- Calling a class encapsulated just because it has getters and setters for every field.