โšกLLD Hub
Learn

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

Private state, public APITypeScript
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

๐Ÿš€ Now apply what you learned

Pick a problem above, write your solution, and get AI feedback on your design.

Start Practice โ†’