TL;DR: OOP is a way of organizing code around things (objects) instead of just steps (functions). Master four ideas, Encapsulation, Abstraction, Inheritance, Polymorphism, and most of the design patterns you meet later will suddenly make sense.
π§ Why am I going back to basics?
Every few months I catch myself using words like "polymorphism" in code reviews while quietly wondering, "wait, can I still explain this to a beginner?"
So I ran an experiment: I let an AI assistant quiz me, challenge my explanations, and rewrite my bad examples. This post is the result: OOP explained the way I wish someone had explained it to me on day one.
All examples are in TypeScript, but the ideas apply to Java, C#, Python, Kotlin, and friends.
π What you'll learn
- What classes and objects really are
- The 4 pillars of OOP (with real-life analogies)
- Composition vs inheritance (the plot twist)
- SOLID in one minute
- How I used AI to modernize my understanding
- Mini quiz + hands-on challenge
β Part 1: The Coffee Shop Analogy
Imagine a coffee shop.
| Coffee shop world | OOP world |
|---|---|
| The recipe for a latte | A class |
| The actual latte in your hand | An object (instance) |
| Size, milk type, temperature | Properties (attributes) |
| Brew, steam, serve | Methods (behaviors) |
A recipe isn't a drink. You can't sip a recipe. But from one recipe you can make a thousand lattes, each slightly different (oat milk, extra shot, iced).
1class Latte { 2 constructor( 3 public size: "S" | "M" | "L", 4 public milk: string, 5 ) {} 6 7 describe(): string { 8 return `A ${this.size} latte with ${this.milk} milk`; 9 } 10} 11 12const morningLatte = new Latte("M", "oat"); 13const lateNightLatte = new Latte("L", "almond"); 14 15console.log(morningLatte.describe()); // A M latte with oat milk 16console.log(lateNightLatte.describe()); // A L latte with almond milk
Key takeaway: a class is a blueprint, an object is a real thing built from it.
ποΈ Part 2: The 4 Pillars of OOP
Think of OOP as a building held up by four pillars. Remove one and things get wobbly.
βββββββββββββββββββββββββββββββββ
β Maintainable Code β
βββββββββββββββββββββββββββββββββ
ββββββββββββββ¬βββββββββββββ¬βββββββββββββ¬βββββββββββββ
βEncapsulat- βAbstraction βInheritance βPolymorph- β
β ion β β β ism β
ββββββββββββββ΄βββββββββββββ΄βββββββββββββ΄βββββββββββββ
π Pillar 1: Encapsulation, "Don't touch my stuff"
Analogy: An ATM. You press buttons; you never reach inside and grab the cash yourself.
Encapsulation means bundling data with the code that works on it, and hiding the internals so outsiders can only use a safe, controlled interface.
1class BankAccount { 2 #balance = 0; // truly private (JS private field) 3 4 deposit(amount: number): void { 5 if (amount <= 0) throw new Error("Deposit must be positive"); 6 this.#balance += amount; 7 } 8 9 withdraw(amount: number): void { 10 if (amount > this.#balance) throw new Error("Insufficient funds"); 11 this.#balance -= amount; 12 } 13 14 get balance(): number { 15 return this.#balance; // read-only from outside 16 } 17} 18 19const account = new BankAccount(); 20account.deposit(100); 21// account.#balance = 1_000_000; β Not allowed!
Why it matters: the rules (no negative deposits, no overdrafts) live in one place. Nobody can accidentally break them.
π€ Click to reveal: What goes wrong without encapsulation?
If balance were a public field, any file in your project could write account.balance = -999. You'd have to hunt down every place that touches it whenever a rule changes. Encapsulation turns "everywhere" into "one place".
π Pillar 2: Abstraction, "Show me the buttons, not the wiring"
Analogy: A car. You use the steering wheel and pedals. You don't need to understand fuel injection to drive to work.
Abstraction means exposing what something does while hiding how it does it. In code, we usually express this with interfaces or abstract classes.
1interface PaymentMethod { 2 pay(amount: number): string; 3}
That's it. Anyone using PaymentMethod only knows there's a pay function. Credit card? E-wallet? Bank transfer? Not their problem.
π‘ Encapsulation vs Abstraction (the classic confusion):
- Encapsulation β hides data to protect it.
- Abstraction β hides complexity to simplify it.
𧬠Pillar 3: Inheritance, "Like parent, like child"
Analogy: A family recipe book. Your grandmother's base dough recipe gets reused (and tweaked) for pizza, bread, and pastries.
Inheritance lets one class reuse and extend another.
1class Notification { 2 constructor(protected recipient: string) {} 3 4 send(message: string): void { 5 console.log(`Sending to ${this.recipient}: ${message}`); 6 } 7} 8 9class EmailNotification extends Notification { 10 send(message: string): void { 11 console.log(`π§ [Email β ${this.recipient}] ${message}`); 12 } 13} 14 15class PushNotification extends Notification { 16 send(message: string): void { 17 console.log(`π± [Push β ${this.recipient}] ${message}`); 18 } 19}
EmailNotification is-a Notification. That "is-a" test is your safety check: if the sentence sounds weird ("a Car is-a Engine"?), inheritance is the wrong tool.
π¦ Pillar 4: Polymorphism, "Same call, different behavior"
Analogy: Press "play" on a TV remote, a music player, or a game console. Same button, completely different result.
Polymorphism means one interface, many implementations. The caller doesn't care which one it gets.
1class CreditCard implements PaymentMethod { 2 pay(amount: number) { return `π³ Charged $${amount} to credit card`; } 3} 4 5class EWallet implements PaymentMethod { 6 pay(amount: number) { return `π² Paid $${amount} via e-wallet`; } 7} 8 9class BankTransfer implements PaymentMethod { 10 pay(amount: number) { return `π¦ Transferred $${amount} from bank`; } 11} 12 13function checkout(method: PaymentMethod, total: number) { 14 console.log(method.pay(total)); // no if/else needed! 15} 16 17checkout(new CreditCard(), 50); 18checkout(new EWallet(), 50); 19checkout(new BankTransfer(), 50);
Without polymorphism, checkout would be a growing tower of if (type === "card") ... else if (type === "ewallet") .... With it, adding a new payment method means adding a class, not editing old code.
π§ͺ Part 3: Mini Quiz (Test Yourself)
Try answering before opening each answer.
Q1. A UserService hides its database connection and only exposes getUser(id). Which pillar is this?
Show answer
Encapsulation (and a bit of abstraction too). The internals are hidden; only a safe interface is exposed.
Q2. You write animals.forEach(a => a.makeSound()) and each animal produces a different sound. Which pillar?
Show answer
Polymorphism. Same method call, different behavior depending on the real object.
Q3. class Penguin extends Bird, but Bird has a fly() method. What's the problem?
Show answer
Penguins can't fly, so Penguin breaks the promise made by Bird. This violates the Liskov Substitution Principle (the "L" in SOLID). Fix: split into Bird and FlyingBird, or use composition.
Q4. True or false: "Inheritance is always the best way to reuse code."
Show answer
False. That's the plot twist in the next section. π
π Part 4: The Plot Twist, Composition over Inheritance
Early in my career I treated inheritance as the hammer for every nail. Deep class trees like Animal β Mammal β Dog β Labrador β ServiceLabrador look elegant... until a requirement changes and half the tree breaks.
The modern advice: favor composition ("has-a") over inheritance ("is-a").
Inheritance way (rigid):
1class OrderService extends Logger { 2 // OrderService "is-a" Logger?? That sounds wrong. 3}
Composition way (flexible):
1interface Logger { 2 log(message: string): void; 3} 4 5class ConsoleLogger implements Logger { 6 log(message: string) { console.log(message); } 7} 8 9class OrderService { 10 constructor(private logger: Logger) {} // "has-a" Logger 11 12 placeOrder(id: string) { 13 this.logger.log(`Order ${id} placed`); 14 } 15} 16 17const service = new OrderService(new ConsoleLogger());
Now you can swap ConsoleLogger for a FileLogger or a FakeLogger in tests, without touching OrderService. This is also the foundation of dependency injection.
| Inheritance | Composition | |
|---|---|---|
| Relationship | "is-a" | "has-a" |
| Coupling | Tight | Loose |
| Flexibility | Fixed at compile time | Swappable at runtime |
| Best for | True hierarchies | Reusing behavior |
π§± Part 5: SOLID in One Minute
SOLID is five guidelines that keep OOP code healthy:
| Letter | Principle | Plain-English version |
|---|---|---|
| S | Single Responsibility | A class should have one reason to change |
| O | Open/Closed | Open for extension, closed for modification |
| L | Liskov Substitution | Subclasses must be usable wherever the parent is expected |
| I | Interface Segregation | Many small interfaces beat one giant one |
| D | Dependency Inversion | Depend on abstractions, not concrete classes |
Notice how the four pillars power SOLID: polymorphism enables Open/Closed, abstraction enables Dependency Inversion, and so on. They're not separate topics, they're one story.
π€ Part 6: How I Used AI to Modernize My Understanding
Here's the part I promised in the title. I didn't just ask the AI "explain OOP" (that gives you a Wikipedia article). I used it as a sparring partner.
Prompts that actually worked
-
The Feynman check
"I'll explain polymorphism as if to a 12-year-old. Find the gaps and confusing parts in my explanation."
-
The code smell hunt
"Here's a class I wrote 2 years ago. Which OOP principles does it violate? Rank by severity and show a refactored version."
-
The analogy generator
"Give me 3 real-world analogies for abstraction, none involving cars."
-
The adversarial quiz
"Quiz me with tricky OOP scenarios. Don't tell me the answer until I commit to one. Then explain what I missed."
-
The modernization pass
"Rewrite this inheritance-heavy code using composition and interfaces. Explain each trade-off."
What AI is great at β
- Generating many examples fast until one finally "clicks"
- Spotting violations you've gone blind to
- Explaining the same idea at different levels
What I learned to double-check β οΈ
- AI can produce over-engineered designs. Not every
ifneeds a Strategy pattern. - It sometimes confidently mixes up similar terms (encapsulation vs abstraction, for example).
- You still have to understand the answer. If you can't explain the refactor to a teammate, you haven't learned it, you've just copied it.
π― My rule: AI drafts, I verify. If I can't explain it back in my own words, it doesn't ship.
π οΈ Part 7: Hands-On Challenge
Time to get your hands dirty. Build a tiny library system:
Requirements
- A
Bookclass withtitle,author, and a privateisBorrowedflag (encapsulation) - A
LibraryIteminterface withgetLoanPeriodDays()(abstraction) -
Book,Magazine, andDVDeach returning a different loan period (polymorphism) - A
Libraryclass that accepts anyLibraryItemwithoutif/elseon type - A
NotificationServiceinjected intoLibraryto remind users about due dates (composition)
Starter skeleton
1interface LibraryItem { 2 title: string; 3 getLoanPeriodDays(): number; 4} 5 6class Book implements LibraryItem { 7 #isBorrowed = false; 8 constructor(public title: string, public author: string) {} 9 10 getLoanPeriodDays() { return 21; } 11 12 borrow() { 13 if (this.#isBorrowed) throw new Error("Already borrowed"); 14 this.#isBorrowed = true; 15 } 16} 17 18// Your turn: Magazine, DVD, Library, NotificationService...
π‘ Need a hint?
Make Library depend on LibraryItem[] and NotificationService (an interface), never on Book or EmailNotificationService directly. Then try swapping in a fake notifier and watch everything still work.
Bonus: paste your solution into an AI assistant and ask: "Which SOLID principles does this follow or break?" Then argue back if you disagree.
π Cheat Sheet
| Concept | One-liner | Keyword to remember |
|---|---|---|
| Class | Blueprint | class |
| Object | Real instance of a class | new |
| Encapsulation | Hide data, expose safe methods | private |
| Abstraction | Hide complexity, expose essentials | interface / abstract |
| Inheritance | Reuse via "is-a" | extends |
| Polymorphism | One call, many behaviors | implements / override |
| Composition | Reuse via "has-a" | constructor injection |
β Final Thoughts
Going back to basics felt humbling and really useful. The fancy stuff, Clean Architecture, design patterns, dependency injection frameworks, is just these four pillars applied with discipline.
If you remember only three things:
- Objects model real things: data + behavior together.
- Depend on abstractions, not concrete details.
- Prefer composition unless you truly have an "is-a" relationship.
"Programs must be written for people to read, and only incidentally for machines to execute.", Harold Abelson
π¬ Your Turn
- Which pillar was the hardest for you to understand at first?
- Did the challenge feel easy, or did it expose gaps?
- Got a better analogy than the coffee shop? I'd love to hear it.
Thanks for reading, and happy coding! π



