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:
| Relationship | Meaning | Notation (text) | Example |
|---|---|---|---|
| Inheritance | is-a | `Car — | > Vehicle` |
| Implementation | implements interface | `Card .. | > PaymentMethod` |
| Composition | owns, part dies with whole | ParkingLot *-- Floor | Floors don’t exist without the lot |
| Aggregation | has, part can live alone | Team o-- Player | Players exist without a team |
| Association | uses / knows about | Ticket --> Spot | A ticket refers to a spot |
| Multiplicity | how many | Floor "1" *-- "many" Spot | One 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
- Turn the
BankAccountinto a design with aTransactionhistory (composition) and an overdraft policy interface. - Draw a class diagram for a library: Book, Copy, Member, Loan, Library. Mark composition vs aggregation.
- Find an inheritance hierarchy in code you know and rewrite part of it with composition.
Quiz
- Why does
withdraw()check the balance instead of letting callers setbalance? - When is inheritance a good fit?
- What’s the difference between composition and aggregation?
Show answers
- Encapsulation: the object enforces its own rule (no negative balance), so invalid states can’t be created from outside.
- For a true “is-a” relationship where the subclass shares stable behaviour with the parent and can be used anywhere the parent is expected.
- 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).