Encapsulation โ Hide the how, expose the what
Keep fields private; mutate state only through methods you control. ยท Callers depend on behaviour, not on how data is stored.
Watch
Watch, then scroll down for code and practice.
In code
class Car {
private speed = 0;
accelerate(delta: number) {
if (delta < 0) return;
this.speed = Math.min(this.speed + delta, 200);
}
getSpeed() {
return this.speed;
}
}๐ Key ideas
What it is
Bundling data (fields) and the methods that operate on it into one unit, and restricting direct access to some of the object's components.
Private fields + public methods
Fields should be private. State should only change through controlled methods. This prevents external code from putting the object into an invalid state.
Why it matters
You can change the internal implementation (e.g. swap a List for a Set) without affecting any caller as long as the public interface stays the same.
Common mistake
Adding a public setter for every private field defeats encapsulation entirely. Expose only what is necessary.
๐ง Practice โ Apply What You Learned
Encapsulation: Car โ Engine โ Wheel
Model a Car that owns an Engine and 4 Wheels. Practice proper encapsulation: fields shouldโฆ
ATM Machine
Design an ATM system that handles card authentication, balance inquiry, cash withdrawal, aโฆ
๐ Now apply what you learned
Pick a problem above, write your solution, and get AI feedback on your design.
Start Practice โ