Loading…
Loading…
Charting your lesson…
Opening your lesson…
Encapsulation and Data Hiding
Lesson 1 of 4
6 steps•about 12 min•11 flashcards
Step 1/ 61 min
Encapsulation is the first of the four OOP pillars and the one most often confused with "using getters and setters". It is really about controlling access to protect an object's internal state — and understanding why is what separates a rote answer from a strong one.
Core idea: encapsulation bundles data and the methods that operate on it into one unit (a class) and restricts direct access to that data, exposing only a controlled public interface. Data hiding is the access-restriction half — making fields private so outside code cannot reach in and corrupt them.
Step 2/ 61 min
class BankAccount {
private double balance; // hidden state
public void deposit(double amt) { // controlled interface
if (amt > 0) balance += amt; // invariant enforced here
}
public double getBalance() { return balance; }
}
The field is private, so no external code can write account.balance = -999. Every change funnels through deposit/withdraw, which can enforce rules.
Most OO languages provide visibility levels (Java example): public (everyone), protected (class + subclasses + package), default/package (same package), private (this class only). C++ uses public/protected/private; Python uses convention (_name "internal", __name name-mangled). The principle is the same: expose the minimum necessary.
The real payoff is class invariants — conditions that must always hold (e.g. balance >= 0). If balance were public, any code could violate the invariant and the bug could originate anywhere. With it private, only the class's own methods can change it, so validation lives in one place and bugs are localised. Encapsulation also enables change without breaking callers: you can switch balance from a field to a computed value, and callers using getBalance() never notice.
// Later: balance becomes derived; the public method shields callers
public double getBalance() { return sumOfTransactions(); }
Step 3/ 61 min
class Temperature {
private double celsius = 0;
public void set(double c) {
if (c < -273.15) throw new IllegalArgumentException("below absolute zero");
celsius = c; // guaranteed valid
}
public double get() { return celsius; }
}
Temperature t = new Temperature();
// t.celsius = -500; // COMPILE ERROR: private -> cannot bypass validation
t.set(25); // allowed
Because celsius is unreachable from outside, every path to change it passes the set guard. Making the field public would let callers create physically impossible states, and you would have no single place to defend the invariant.
Step 4/ 61 min
Common asks: "what is encapsulation and how is it different from abstraction?" (encapsulation hides data and bundles behaviour; abstraction hides complexity/implementation), "why are getters/setters used?" (controlled access, validation, future flexibility), and access-modifier semantics. A strong answer stresses invariants, not just "make fields private".
Step 5/ 61 min
List) breaks encapsulation — callers can mutate it directly; return a copy or an unmodifiable view.protected is more open than beginners expect (often package-visible too).Equating encapsulation with "just add getters and setters". Blindly exposing every field through a setter that does no validation is barely better than making the field public — you have preserved none of the protection. Encapsulation's point is a controlled interface that guards invariants, not mechanical accessor generation.
public/protected/private) express the minimum-exposure principle.Step 6/ 6· Worked examples2 min
Problem
A BankAccount exposes its balance as a public field, and a bug lets the balance go negative. Redesign it with encapsulation so the invariant "balance ≥ 0" cannot be violated, and explain what data hiding buys you.
// Before: no protection
class BankAccount { public double balance; }
acct.balance = -500; // nothing stops this
Try it on paper first.
Recall
Keep this
Encapsulation is the first of the four OOP pillars and an interview certainty — "name the pillars of OOP and explain encapsulation" opens countless rounds. It shows you can design classes that protect their own invariants.
Encapsulation bundles data (fields) and the methods that operate on them into a single unit (the class), and restricts direct access to the internal state. The outside world interacts only through a controlled public interface (getters/setters/methods) — the object guards its own consistency.
Data hiding is the access-control part: marking fields private so they can't be read/written directly, only via methods that can validate.
| Modifier | Visible to |
|---|---|
| private | same class only |
| protected | class + subclasses (+ package in Java) |
| public | everyone |
| (default/package) | same package (Java) |
Encapsulation lets you change internal implementation without breaking callers, enforce invariants (e.g. a setter validates that age ≥ 0), and reduce coupling — the hallmark of maintainable code.
_x is a convention, and __x triggers name-mangling, not real hiding.private is the most restrictive, public the least; protected sits between (adds subclasses)."Define encapsulation", "encapsulation vs abstraction", "why make fields private?", "list access modifiers", and "how does Python do encapsulation?".
Encapsulation bundles data + behaviour in a class and restricts direct access (data hiding via private). Interact through getters/setters that can validate. Modifiers: private < protected < public. It cuts coupling and lets internals change freely. Distinct from abstraction (which hides complexity).
You've read 0 of 6 steps
Now lock it in — questions straight after reading are what make it stick.