The 4 pillars of OOP

Encapsulation, abstraction, inheritance and polymorphism sound like words to memorize. Watch them on one small parcel shop instead: what problem each one stops, and why inheriting your way out of everything ends badly.

Level: BasicWatch: 17 steps · ~75 secondsAsk for prices, add parts, sneak a status changeRecall: 3 questions · 8 cardsCompare inheritance · compositionTypeScript · Java · Kotlin · Python · Go

What you'll take away

  • Hide state behind methods that check the rules, so deliver() waits for pickUp()
  • Tell encapsulation from abstraction: guarding the inside vs choosing what shows
  • Use polymorphism so one quote() call works on every courier with no if per vehicle
  • Spot subclasses multiplying, and switch to composition: a courier that has parts

The 1-minute version

Tap a point and the picture below plays that step.

4Compare them all
Class & objecta plan, and things made from it
shop
class Parcel
new Parcel("TH-001", 2) → …
Step 1 / 17 · step by step
0Parcels made
0Delivered
–Last quote
2Courier classes

The shop, the couriers and the parcels are made up for this lesson, and so are the prices. In the workshop a workbench is a class and a lilac belt with a hollow head means "extends"; out on the street the crates are parcel objects and the lights are calls.

Step 4 · Every option at once, on one clock

Compare them all: Inheritance vs composition

The shop has two vehicles, and new needs arrive one at a time: cold, insured, live tracking, express. Left: inheritance, a subclass for every mix. Right: composition, a courier has parts instead. Count the classes you'd write.

no features yet
Inheritance (is-a)class ColdInsuredTruck extends Truckclasses 3 · next feature adds 2

Use it when Something that really is a kind of another, in a shallow hierarchy that rarely changes

Skip it when You need to mix several abilities: the classes multiply, and changing the parent touches every child

A plain count: inheritance = 1 + 2 vehicles × 2^features, composition = 1 + 2 vehicles + one per part. Press any tile to see it large above, with when it fits.

The four, one line each

IdeaWhat it doesIn this shop
EncapsulationHides the state and opens only doors that check the rulesstatus changes only through pickUp() and deliver()
AbstractionShows users only what they needThe shop knows a Courier only by quote() and ship()
InheritanceChildren get the parent's codeMotorbike and Truck get track() from Courier
PolymorphismThe same call, different answersOne quote(), each vehicle's own price

Composition before inheritance

Inherit when a thing really is a kind of another, in a shallow hierarchy. Otherwise, let it have parts: any mix works without a new class, and changing one part doesn't ripple through a whole tree.

Each language does it its own way

Java and Kotlin have a real private that the compiler enforces. TypeScript has #field, enforced at run time too. Python has no real private, just the _ convention. Go has no classes at all: structs, interfaces and embedding, with hiding per package.

In real code

parcel.ts
// The four ideas of OOP on one small shop: a Parcel guards its status, couriers share tracking and price their own way.
// Run: node parcel.ts   (Node 23.6+; on Node 22: node --experimental-strip-types parcel.ts)
import assert from "node:assert/strict";

type Status = "waiting" | "picked" | "delivered";

class Parcel {
  #status: Status = "waiting"; // encapsulation: nothing outside the class can set it
  readonly id: string;
  readonly kg: number;
  constructor(id: string, kg: number) { this.id = id; this.kg = kg; }
  get status(): Status { return this.#status; }
  pickUp() { if (this.#status !== "waiting") throw new Error("already picked up"); this.#status = "picked"; }
  deliver() { if (this.#status !== "picked") throw new Error("not picked up yet"); this.#status = "delivered"; }
}

// Abstraction: all the shop gets to know about a courier.
interface Courier {
  readonly name: string;
  quote(p: Parcel): number | null; // null: can't take it
  ship(p: Parcel): string;
}

// Inheritance: what every courier shares, written once.
abstract class BaseCourier implements Courier {
  abstract readonly name: string;
  abstract quote(p: Parcel): number | null;
  ship(p: Parcel) { p.pickUp(); return this.track(p); }
  protected track(p: Parcel) { return `${this.name} has ${p.id} (${p.status})`; }
}
class Motorbike extends BaseCourier {
  readonly name = "Motorbike";
  quote(p: Parcel) { return p.kg > 10 ? null : 30 + Math.ceil(p.kg) * 8; }
}
class Truck extends BaseCourier {
  readonly name = "Truck";
  quote(p: Parcel) { return 90 + Math.ceil(p.kg) * 3; }
}

// Polymorphism: one call for every courier; each answers its own way.
const couriers: Courier[] = [new Motorbike(), new Truck()];
const quotes = (p: Parcel) => couriers.map((c) => `${c.name} ${c.quote(p) ?? "can't"}`).join(", ");

const small = new Parcel("TH-001", 2), heavy = new Parcel("TH-002", 20);
assert.equal(quotes(small), "Motorbike 46, Truck 96");
assert.equal(quotes(heavy), "Motorbike can't, Truck 150");
assert.throws(() => small.deliver(), /not picked up/); // the order is guarded
const shipped = couriers[0].ship(small);
small.deliver();
assert.equal(small.status, "delivered"); // small.#status = "picked" would not even compile
console.log(`2 kg: ${quotes(small)} · 20 kg: ${quotes(heavy)} · ${shipped} → delivered`);
Run: node parcel.ts (Node 23.6+ · on Node 22 add --experimental-strip-types)It printed: 2 kg: Motorbike 46, Truck 96 · 20 kg: Motorbike can't, Truck 150 · Motorbike has TH-001 (picked) → delivered

The same shop in five languages, all printing the same line: status is private (Python uses _ and a property; Go hides per package), Courier is an interface, track() is written once in the parent class, and each vehicle's quote() answers its own way. Go has no classes, so it uses structs, interfaces and embedding instead.

Common questions

What are the four pillars of OOP?

Encapsulation hides the state and opens only doors that check the rules. Abstraction shows users only what they need. Inheritance gives children the parent's code. Polymorphism is one call that each kind answers its own way.

Aren't encapsulation and abstraction the same thing?

No. Encapsulation guards the inside: status is private and only methods that check the order can change it. Abstraction decides what the outside sees: the shop knows a Courier only by quote() and ship(), not its route. One stops breakage, the other stops you needing to know too much.

What is polymorphism, in plain words?

You call the same method on different kinds of thing, and each answers its own way. The shop calls quote() on every vehicle; the motorbike and the truck price it differently, and for 20 kg the motorbike says itself that it can't take it.

What does "composition over inheritance" mean?

Inheritance is is-a, composition is has-a. With a subclass for every mix, four features on two vehicles already means 33 classes. Give the courier parts instead and it's 7 classes in all, with no new one for any mix.

So when is inheritance the right call?

When the thing really is a kind of the other, in a shallow hierarchy that rarely changes: Motorbike and Truck are Couriers and get track() for free. Once you need to mix several abilities, that's your cue for composition.

Read: composition before inheritance

What's the difference between a class and an object?

A class is the plan, an object is a thing made from it. Parcel says a parcel has a weight, a status and things it can do; each box in the shop is an object with its own values.

Is private the same in every language?

No. Java and Kotlin have a real private that the compiler enforces. TypeScript has #field, enforced at run time too. Python has no real private, only the _ convention. Go has no classes at all and hides things per package.

Read: each language does it its own way

Next lesson

Design patternsLevel: Intermediate

Interfaces, polymorphism and composition are the parts; next, design patterns, the named fixes built from them, and when to skip each.