Lesson 2 of 12 Foundations

OOP Essentials and Class Diagrams

The OOP ideas LLD relies on: encapsulation, abstraction, polymorphism, composition over inheritance, and reading and drawing UML class diagrams.

30-40 min beginner 0/12 lessons done
Course contents Lesson 2 of 12 · 0 done
On this page (7 sections)
  1. What you will learn
  2. The pillars, practically
  3. Composition over inheritance
  4. Class diagrams in five minutes
  5. Key takeaways
  6. Exercises
  7. Quiz

What you will learn

  • The four OOP pillars, framed for design rather than definitions.
  • Composition vs inheritance, and why composition usually wins.
  • The relationships in a class diagram and how to draw them quickly in an interview.

The pillars, practically

Encapsulation: an object owns its data and enforces its rules. A BankAccount exposes withdraw(amount), which checks the balance, rather than letting callers set balance directly. Invalid states become impossible instead of merely discouraged.

class BankAccount:
    def __init__(self, owner: str):
        self.owner = owner
        self._balance = 0  # underscore: internal, change it through methods only

    @property
    def balance(self) -> int:
        return self._balance

    def deposit(self, amount: int) -> None:
        if amount <= 0:
            raise ValueError("deposit must be positive")
        self._balance += amount

    def withdraw(self, amount: int) -> None:
        if amount > self._balance:
            raise ValueError("insufficient funds")
        self._balance -= amount

Abstraction: callers depend on what something does, not how. A PaymentMethod interface with pay(amount) hides whether it’s a card, UPI or wallet.

Inheritance: a subclass reuses and specialises a parent. Useful for true “is-a” relationships with shared behaviour, but easy to overuse.

Polymorphism: code written against an interface works with any implementation. for m in payment_methods: m.pay(100) doesn’t care which concrete types are in the list.

Composition over inheritance

Inheritance couples a child to its parent’s internals; deep hierarchies become rigid (“a FlyingSwimmingDuck extends…”). Composition builds behaviour from parts:

class Engine:
    def start(self) -> str:
        return "engine on"


class ElectricMotor:
    def start(self) -> str:
        return "motor humming"


class Car:
    def __init__(self, power_source):
        self.power = power_source  # has-a, swappable at construction

    def drive(self) -> str:
        return self.power.start() + ", driving"


print(Car(Engine()).drive())         # engine on, driving
print(Car(ElectricMotor()).drive())  # motor humming, driving

Rule of thumb: inherit for a genuine “is-a” with stable shared behaviour (a Truck is a Vehicle); compose for “has-a” or “uses” and whenever behaviour should vary independently.

Class diagrams in five minutes

In an interview you don’t need perfect UML, just a clear picture. A class box lists name, key fields and key methods:

+---------------------------+
| ParkingLot                |
+---------------------------+
| - floors: list[Floor]     |
| - active: dict[str,Ticket]|
+---------------------------+
| + park(v): Ticket         |
| + leave(plate): Ticket    |
+---------------------------+

+ is public, - private. Relationships:

RelationshipMeaningNotation (text)Example
Inheritanceis-a`Car —> Vehicle`
Implementationimplements interface`Card ..> PaymentMethod`
Compositionowns, part dies with wholeParkingLot *-- FloorFloors don’t exist without the lot
Aggregationhas, part can live aloneTeam o-- PlayerPlayers exist without a team
Associationuses / knows aboutTicket --> SpotA ticket refers to a spot
Multiplicityhow manyFloor "1" *-- "many" SpotOne floor, many spots

In practice: draw boxes for the 5–8 main classes, connect them with labelled arrows, mark the interfaces, and move on to code.

Key takeaways

  • Encapsulation protects invariants; abstraction and polymorphism let you swap implementations.
  • Prefer composition; inherit only for real “is-a” with shared, stable behaviour.
  • Class diagrams need only names, key fields/methods and relationships with multiplicity.

Exercises

  1. Turn the BankAccount into a design with a Transaction history (composition) and an overdraft policy interface.
  2. Draw a class diagram for a library: Book, Copy, Member, Loan, Library. Mark composition vs aggregation.
  3. Find an inheritance hierarchy in code you know and rewrite part of it with composition.

Quiz

  1. Why does withdraw() check the balance instead of letting callers set balance?
  2. When is inheritance a good fit?
  3. What’s the difference between composition and aggregation?
Show answers
  1. Encapsulation: the object enforces its own rule (no negative balance), so invalid states can’t be created from outside.
  2. For a true “is-a” relationship where the subclass shares stable behaviour with the parent and can be used anywhere the parent is expected.
  3. In composition the part’s lifetime is bound to the whole (floors of a parking lot); in aggregation the part can exist independently (players and teams).

Finished this lesson?

Mark it complete to track your progress (saved in this browser).