OOP Concepts
Every low-level design interview is an object-oriented programming test in disguise. When the interviewer asks
"where does this rule live?", they are asking about encapsulation. "How would you add a new payment method?" is
about polymorphism. "Why does Truck extend Car?" is about inheritance, and usually a hint that it shouldn't.
You probably know the textbook definitions. What interviews test is whether you can use them: pick the right tool for a design decision and explain why. This post covers the core ideas, each in plain words, with a small Bad/Good code pair from a realistic problem and what the bad version costs you.
π‘ How to use this in an interview: you don't get points for saying "encapsulation". You get points for a
BankAccountwhose balance can't go negative no matter who calls it. Name the concept only when it explains a choice.
Classes and Objects
A class describes a kind of thing: what data it holds (its state, stored in fields) and what it can do (its
behavior, written as methods). An object is one concrete instance of a class. ParkingSpot is a class;
spot "L1-07" on level 1 is an object.
The point of putting state and behavior together is that the methods can protect the data. A spot knows whether it is free, and only the spot's own methods change that. Everything else in this post builds on that one idea.
class ParkingSpot:
def __init__(self, spot_id: str) -> None:
self.spot_id = spot_id
self.vehicle: str | None = None # plate of the parked vehicle
def is_free(self) -> bool:
return self.vehicle is None
def assign(self, plate: str) -> None:
if not self.is_free():
raise ValueError(f"{self.spot_id} is taken")
self.vehicle = plate
Encapsulation
Encapsulation means an object keeps its data private and lets the outside world change it only through methods that check the rules. The rules an object must always satisfy are called its invariants. For a bank account: the balance is never negative, and every change is recorded.
Bad:
class BankAccount:
def __init__(self, owner: str) -> None:
self.owner = owner
self.balance = 0
self.history: list[int] = []
# somewhere else in the code
account.balance -= 500 # no check, no history entry
account.history.append(-500) # if the caller remembers
What the bad version costs you. Any line of code anywhere can break the invariants. The "balance can't go negative" rule must be repeated by every caller, and the day one caller forgets, the account goes to -500 and nobody knows which code did it.
Good:
class BankAccount:
def __init__(self, owner: str) -> None:
self.owner = owner
self._balance = 0
self._history: list[int] = []
@property
def balance(self) -> int:
return self._balance
def deposit(self, amount: int) -> None:
if amount <= 0:
raise ValueError("amount must be positive")
self._balance += amount
self._history.append(amount)
def withdraw(self, amount: int) -> None:
if amount <= 0 or amount > self._balance:
raise ValueError("invalid amount")
self._balance -= amount
self._history.append(-amount)
The rules live in one place, and there is no way around them. Callers can read the balance but not set it.
Python has no private keyword; a leading underscore is the convention that says "don't touch this from outside",
and a @property exposes a read-only view. In Java you would write private int balance; and a getBalance()
method, with no setter.
When not to apply it. Plain data with no rules doesn't need guarding. A Coordinate(x, y) or an Address is
fine as a dataclass with public fields; wrapping each field in a getter and setter adds code and protects nothing.
Encapsulate where there is an invariant to protect. A useful middle ground is an immutable value: a frozen
dataclass can't be changed at all, so it needs no guards.
β οΈ Common mistake: adding a getter and a setter for every field and calling it encapsulation. A
set_balance()that anyone can call is the same as a public field. Expose operations (deposit,withdraw), not fields.
Abstraction
Abstraction means showing callers what an object does and hiding how it does it. The caller sees a small, simple interface; the messy steps stay inside. Encapsulation protects the data; abstraction simplifies the use.
Bad:
def checkout(cart: Cart, card_number: str) -> None:
token = http_post("https://pay.example/tokens", {"card": card_number})["token"]
for attempt in range(3):
resp = http_post("https://pay.example/charges", {"token": token, "cents": cart.total()})
if resp["status"] != "retry":
break
if resp["status"] != "ok":
raise PaymentError(resp["error"])
cart.mark_paid(resp["charge_id"])
What the bad version costs you. The checkout code knows the provider's URLs, its token step, its retry behavior and its response format. A second place that charges money (subscriptions, refunds) copies all of it. If the provider changes an endpoint, every copy breaks.
Good:
class PaymentGateway:
def charge(self, card_number: str, cents: int) -> str:
"""Charges the card and returns a charge id. Raises PaymentError on failure."""
token = self._tokenize(card_number)
return self._charge_with_retries(token, cents)
def _tokenize(self, card_number: str) -> str: ...
def _charge_with_retries(self, token: str, cents: int) -> str: ...
def checkout(cart: Cart, card_number: str, gateway: PaymentGateway) -> None:
charge_id = gateway.charge(card_number, cart.total())
cart.mark_paid(charge_id)
checkout now reads like the business rule it is: charge the total, mark the cart paid. How charging works is one
class's problem.
When not to apply it. An abstraction that hides nothing is just indirection. A CartTotalCalculator with one
method that returns sum(item.price for item in items) adds a class and a name to learn, and saves nothing.
Abstract the parts that are complicated or likely to change: external services, storage, algorithms with
variants.
Inheritance
Inheritance lets one class (the subclass) reuse and extend another (the base class or parent). The
subclass gets the parent's fields and methods and can add or override some. It models an is-a relationship: a
SavingsAccount is a BankAccount.
Used well, inheritance removes duplication between types that genuinely share behavior. Used badly, it builds deep trees where a change at the top breaks things at the bottom.
Bad:
class Employee:
def pay(self) -> int: return self.salary
class Manager(Employee):
def pay(self) -> int: return super().pay() + self.team_bonus
class RemoteManager(Manager):
def pay(self) -> int: return super().pay() + REMOTE_STIPEND
class ContractRemoteManager(RemoteManager):
def pay(self) -> int: return self.hourly_rate * self.hours # ignores everything above
What the bad version costs you. To know what ContractRemoteManager.pay() does you have to read four classes.
The last one throws away its parents' logic, so it only inherits to get the type, which is a sign the hierarchy is
wrong. And "remote" and "contract" are independent facts, so every combination needs its own class: remote
engineer, contract engineer, contract remote engineer, and so on.
Good:
class Employee:
def __init__(self, name: str, pay_plan: PayPlan, perks: list[Perk]) -> None:
self.name = name
self.pay_plan = pay_plan # Salaried, Hourly, ...
self.perks = perks # TeamBonus, RemoteStipend, ...
def pay(self) -> int:
return self.pay_plan.base_pay() + sum(p.amount() for p in self.perks)
Role, contract type and location are now separate parts you combine, not branches of a family tree. That is composition, the next section.
When inheritance is the right tool. Keep it shallow (one level is the sweet spot, two at most) and use it when the subclass truly is a special case of the parent and keeps every promise the parent makes (the Liskov rule in Design Principles). A good test: can every piece of code that uses the parent take the subclass without checking its type? If yes, inherit. If you find yourself overriding a method to throw an error or to ignore the parent, don't.
Composition over Inheritance
Composition means building an object out of other objects it holds as fields, and delegating work to them. Instead of being something, the object has something. "Prefer composition over inheritance" is one of the most useful rules in LLD, because it turns a tree of combinations into a few parts you can mix.
Here is a game where characters differ in how they attack and how they defend.
Bad:
class Character: ...
class SwordFighter(Character): ...
class Archer(Character): ...
class ShieldedSwordFighter(SwordFighter): ...
class ShieldedArcher(Archer): ...
class ArmoredSwordFighter(SwordFighter): ...
class ArmoredArcher(Archer): ...
# a new weapon (staff) means three more classes; a new defense means one per weapon
What the bad version costs you. The number of classes is weapons Γ defenses and grows with every new item. A character can't pick up a bow mid-game, because an object can't change its class. Shared logic like "how shield blocks work" is copied into every shielded subclass.
Good:
class Weapon(ABC):
@abstractmethod
def damage(self) -> int: ...
class Defense(ABC):
@abstractmethod
def reduce(self, incoming: int) -> int: ...
class Character:
def __init__(self, name: str, weapon: Weapon, defense: Defense) -> None:
self.name = name
self.weapon = weapon
self.defense = defense
self.health = 100
def attack(self, target: "Character") -> None:
target.take_hit(self.weapon.damage())
def take_hit(self, incoming: int) -> None:
self.health -= self.defense.reduce(incoming)
def equip(self, weapon: Weapon) -> None:
self.weapon = weapon # change behavior at run time
Now there is one Character class, and weapons and defenses are added one class at a time. A new weapon is one new
class that works with every defense. Each part is also small enough to test on its own.
When not to apply it. If there is only one dimension of variation and it will not change at run time, a
shallow inheritance tree is simpler. Circle, Square and Triangle extending Shape with an area() method is
perfectly fine; there is nothing to compose. Reach for composition when you see two independent dimensions, or when
behavior has to change while the program runs.
π― A quick test in interviews: if you are about to name a class with two qualifiers (
ShieldedArcher,RemoteContractManager,ExpressInternationalShipment), you have two dimensions. Turn at least one into a part the object holds.
Polymorphism
Polymorphism means "many forms": code calls the same method on different objects, and each object responds in its own way. The caller doesn't need to know which kind it has. This is what lets you add a new type without editing the code that uses it.
Bad:
class NotificationService:
def send(self, user: User, message: str, channel: str) -> None:
if channel == "email":
smtp_send(user.email, message)
elif channel == "sms":
sms_api(user.phone, message[:160])
elif channel == "push":
push_api(user.device_token, message)
else:
raise ValueError(channel)
What the bad version costs you. Every new channel edits this method, and every other method that branches on
channel (retry rules, cost tracking, opt-out checks) grows the same if chain. Forget one and the new channel
half works.
Good:
class Channel(ABC):
@abstractmethod
def send(self, user: User, message: str) -> None: ...
class EmailChannel(Channel):
def send(self, user: User, message: str) -> None:
smtp_send(user.email, message)
class SmsChannel(Channel):
def send(self, user: User, message: str) -> None:
sms_api(user.phone, message[:160])
class NotificationService:
def send(self, user: User, message: str, channel: Channel) -> None:
channel.send(user, message)
A Slack channel is one new class. NotificationService never changes. This is the
Strategy Pattern in its simplest form, and it is the most common use of
polymorphism in LLD answers.
There are two kinds of polymorphism you may be asked to name:
- Run-time polymorphism (overriding): a subclass replaces a parent's method, and the call picks the version based on the object's actual type while the program runs. Everything above is this kind.
- Compile-time polymorphism (overloading): several methods share a name but take different parameter types,
and the compiler picks one. Java and C++ support it; Python doesn't (a later
defwith the same name replaces the earlier one).
class Receipt {
String format(int cents) { return String.format("$%d.%02d", cents / 100, cents % 100); }
String format(Order order) { return order.id() + ": " + format(order.totalCents()); }
}
When not to apply it. If the variants differ only in data, use data. Hourly parking rates per vehicle type are
a dictionary, not a class per vehicle. And a two-case if that will never grow (a door is open or closed) is
clearer than two classes.
Interfaces and Abstract Classes
An interface is a contract: a list of methods a class promises to provide, with no fields and (traditionally) no code. An abstract class is a partly written class: it can hold fields and finished methods, and it leaves some methods for subclasses to fill in. Neither can be instantiated on its own.
This is one place where the language matters, so here is Java, where the difference is explicit.
interface PaymentMethod { // a contract: what, not how
String charge(int cents);
void refund(String chargeId);
}
abstract class CardPayment implements PaymentMethod { // shared state and steps
protected final String cardNumber;
CardPayment(String cardNumber) { this.cardNumber = cardNumber; }
public String charge(int cents) {
validateCard(); // the same for every card network
return submit(cents); // differs per network
}
private void validateCard() { /* Luhn check, expiry */ }
protected abstract String submit(int cents);
}
class VisaPayment extends CardPayment {
VisaPayment(String cardNumber) { super(cardNumber); }
protected String submit(int cents) { /* call the Visa API */ return "visa-123"; }
public void refund(String chargeId) { /* ... */ }
}
PaymentMethod lets a Checkout accept cards, wallets and bank transfers without knowing which. CardPayment
holds what every card has in common (the number, the validation step) so it is written once.
| Interface | Abstract class | |
|---|---|---|
| Holds state (fields) | No (constants only) | Yes |
| Holds code | Only default methods (Java 8+) |
Yes, any |
| A class can have | Many | One parent (Java, C#) |
| Use it for | A capability or role: Payable, Comparable, Channel |
A family that shares state and steps |
In Python, both are written with ABC and @abstractmethod, and a class can inherit from several. There is also
typing.Protocol for structural interfaces: a class satisfies it just by having the right methods, without
inheriting from it, much like Go's interfaces.
Bad:
class PaymentMethod(ABC):
def __init__(self) -> None:
self.card_number = "" # wallets and bank transfers have no card number
self.retries = 3
@abstractmethod
def charge(self, cents: int) -> str: ...
What the bad version costs you. The base class forces card-specific state onto every payment method. A
WalletPayment inherits a card_number it can never fill, and every reader wonders what it means there.
Good:
class PaymentMethod(ABC): # the contract only
@abstractmethod
def charge(self, cents: int) -> str: ...
class CardPayment(PaymentMethod, ABC): # state shared by cards only
def __init__(self, card_number: str) -> None:
self.card_number = card_number
Which to choose. Start with an interface. It is the smallest promise and leaves implementers free. Move shared code into an abstract class only when two or more implementations really share fields and steps. If you are not sure, the interface is the safer choice: adding an abstract class under it later is easy, and removing one is not.
π‘ Interview tip: in Java,
interfaceversusabstract classis a classic quick question. A crisp answer: "An interface says what a class can do; an abstract class shares how. A class can implement many interfaces but extend one class, so I use interfaces for roles and abstract classes for families with shared state."
OOP in an Interview
These ideas show up in every part of an LLD round, usually without anyone naming them.
During class design, encapsulation decides where each rule lives: the class that owns the data enforces the
rule about it. If you write spot.vehicle = plate from inside ParkingLot, your interviewer sees a rule leaking
out of its owner. Write spot.assign(plate) instead.
When you see variants, polymorphism and composition decide the shape. Several kinds of the same thing that behave differently (payment methods, pricing rules, notification channels) become an interface with one class per kind. Two independent dimensions (weapon and defense) become two parts the object holds.
In follow-ups, the payoff shows. "Add a new channel" is one new class. "Let a character switch weapons" is
one equip call. If a follow-up forces you to edit five if chains, your design is telling you where polymorphism
was missing.
| What you see in your code | Concept that fixes it |
|---|---|
| Other classes setting your fields directly | Encapsulation: expose operations, not fields |
| Callers that know a service's internal steps | Abstraction: one method that hides the steps |
An if/elif chain on a type string |
Polymorphism: one class per type behind an interface |
| Class names with two qualifiers | Composition: turn one dimension into a held part |
| A subclass that overrides a method to throw | Smaller interfaces, or composition instead of inheritance |
| A base class with fields some children can't use | Interface for the contract, abstract class only for real shared state |
Summary
- Classes and objects: a class bundles state with the methods that protect it; an object is one instance.
- Encapsulation: keep data private and change it only through methods that enforce the invariants. Expose operations, not setters.
- Abstraction: show callers what an object does, hide how. Abstract what is complex or likely to change.
- Inheritance: for true is-a relationships that keep the parent's promises. Keep it shallow.
- Composition over inheritance: when there are independent dimensions, or behavior changes at run time, hold parts instead of inheriting from them.
- Polymorphism: the same call, different behavior per type, so a new type is a new class and callers don't change.
- Interfaces versus abstract classes: interfaces for roles and contracts, abstract classes for families that share state and steps. Start with an interface.