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.
What you'll take away
- Hide state behind methods that check the rules, so
deliver()waits forpickUp() - 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.
Motorbike: Quick and cheap for small things, up to 10 kg · Truck: Costs more to start, but cheap per kilo for heavy things · Parts: cold 40 + 2 a kilo, insured 25, live tracking 15, express 60 baht
The parcel's status is private and only changes through pickUp() and deliver(). Which idea is that, and what does it buy you?
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.
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.
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
| Idea | What it does | In this shop |
|---|---|---|
| Encapsulation | Hides the state and opens only doors that check the rules | status changes only through pickUp() and deliver() |
| Abstraction | Shows users only what they need | The shop knows a Courier only by quote() and ship() |
| Inheritance | Children get the parent's code | Motorbike and Truck get track() from Courier |
| Polymorphism | The same call, different answers | One 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
// 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`);
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) → deliveredThe 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.
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.
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.