OOP (object-oriented programming) and SOLID questions come up in every low-level design (LLD) round, usually as "what is the Open/Closed principle?" followed by "show me where your design follows it". Reciting the names is not enough. You need to be able to point at a class and say which principle it serves and what change it makes cheap. This lesson uses one example, a checkout, and shows each principle with code without it and with it. The code is tested.
1. Object-Oriented Design in Four Ideas
Each idea answers a specific problem. In an interview, name the problem before the idea. The examples are parts of one checkout.
Encapsulation: an object cannot be put into a bad state
What it is: bundling data with the code that works on it, and hiding the data behind methods so only valid changes are possible.
If amounts travel as plain long values, nothing stops a -5 from reaching the payment code, and every method has to check. Put the rule in one class that nobody can bypass:
record Money(long cents) {
Money {
if (cents < 0) throw new IllegalArgumentException("money cannot be negative");
}
Money plus(Money other) { return new Money(cents + other.cents); }
Money minus(Money other) { return new Money(cents - other.cents); } // refuses to go below zero
}
The constructor refuses a negative amount, and the object never changes after creation (plus returns a new Money), so a Money that exists is always valid.
Abstraction: depend on what it does, not how
What it is: exposing a simple interface that says what something does, and hiding how it does it.
The checkout wants one thing from a payment: "charge this amount". Payment offers exactly that and hides everything else: the gateway, retries, the voucher database. Replace the card gateway and the checkout does not notice. Name an abstraction for the caller's need (Payment, Notifier), not for the implementation (StripeClient).
@FunctionalInterface
interface Payment {
// Charges a positive amount in cents and returns a transaction id.
// Throws IllegalArgumentException if cents <= 0.
String charge(long cents);
}
Polymorphism: one call, different behaviour
What it is: many classes sharing one interface, so the same call runs different code depending on the object behind it. It removes if (type == ...) from the caller.
A customer may want email and SMS. Instead of branching on channel, treat a list of channels as one notifier:
@FunctionalInterface
interface Notifier {
void send(String to, String message);
}
class CompositeNotifier implements Notifier {
private final List<Notifier> channels;
CompositeNotifier(List<Notifier> channels) { this.channels = List.copyOf(channels); }
@Override public void send(String to, String message) {
for (Notifier channel : channels) channel.send(to, message);
}
}
The loop has no condition on the channel, and adding push means adding one class. CompositeNotifier is also a Notifier, so the checkout cannot tell one channel from three. This is overriding, or runtime polymorphism: the version that runs depends on the actual object.
Overloading is different: the same method name with different parameters. It is compile-time polymorphism, because the compiler picks the version from the declared argument types before the program runs:
class Receipt {
String format(long cents) { return "Rs " + cents / 100; }
String format(Money amount) { return format(amount.cents()); }
}
format(2500) and format(new Money(2500)) both give Rs 25. Overloading is a convenience for callers, not a design tool.
Composition vs aggregation vs association vs inheritance
These describe how one class relates to another. The first three are "has a" or "uses" relationships. Only inheritance is "is a".
| Relationship | Meaning | Example |
|---|---|---|
| Association | One class uses another, with no ownership | Checkout.place receives a Payment as a parameter |
| Aggregation | Has a part that lives on its own | Checkout holds an OrderStore that was created elsewhere and passed in |
| Composition | Owns a part that dies with it | An Order creates its OrderLine objects, and they go when the order goes |
| Inheritance | Is a kind of the parent, and gets all of it | Java's Stack extends Vector |
Aggregation and composition look the same in code. The difference is who creates the part and what happens to it when the owner goes. Inheritance ties the child to the parent's internals: Stack lets you insert in the middle, because Vector does, and that breaks what a stack is.
So prefer holding objects over extending classes. To log every payment charge, inheritance needs LoggingCardPayment, LoggingGiftCardPayment and one more for every new method. With composition, one small class wraps any payment:
class LoggingPayment implements Payment {
private final Payment inner;
private final Consumer<String> log;
LoggingPayment(Payment inner, Consumer<String> log) { this.inner = inner; this.log = log; }
@Override public String charge(long cents) {
log.accept("charging " + cents);
return inner.charge(cents);
}
}
new LoggingPayment(new CardPayment(), log::add) is a logged card payment, and the same wrapper works for every other payment. It logs before charging, so a failed charge is logged too. Rule of thumb: inherit only when the child can replace the parent everywhere the parent is used. To add behaviour or reuse code, compose.
2. SOLID, One Letter at a Time
SOLID is five principles: Single responsibility, Open/closed, Liskov substitution, Interface segregation and Dependency inversion. Each example below stands on its own, with the code without the principle and with it.
S: Single Responsibility
A class should have one reason to change. Ask: "who would ask me to change this class?" If the answer is several different people or teams, split it.
Without: this checkout changes when payment rules change, when the database changes and when the email wording changes. It also cannot be tested, because its database and mail calls are real.
class CheckoutBefore {
String place(String orderId, String email, long cents) {
String tx = CardGateway.charge(cents); // payment rules
Database.save(orderId, cents); // storage
SmtpMailer.send(email, "Order " + orderId + " confirmed"); // messaging
return tx;
}
}
With: each reason gets its own class, and the checkout only coordinates them:
class PaymentService {
String charge(long cents) { return CardGateway.charge(cents); }
}
class OrderRepository {
void save(String orderId, long cents) { Database.save(orderId, cents); }
}
class EmailService {
void sendConfirmation(String email, String orderId) {
SmtpMailer.send(email, "Order " + orderId + " confirmed");
}
}
class Checkout {
private final PaymentService payments;
private final OrderRepository orders;
private final EmailService emails;
Checkout(PaymentService payments, OrderRepository orders, EmailService emails) {
this.payments = payments;
this.orders = orders;
this.emails = emails;
}
String place(String orderId, String email, long cents) {
String tx = payments.charge(cents);
orders.save(orderId, cents);
emails.sendConfirmation(email, orderId);
return tx;
}
}
O: Open/Closed
Code should be open to extension and closed to modification: adding a behaviour means adding a class, not editing a working one.
Without: every new payment type adds a branch to the same if chain, and every edit risks the existing branches:
class CheckoutBefore {
String charge(String paymentType, long cents) {
if (paymentType.equals("CARD")) {
return "card-" + cents;
} else if (paymentType.equals("GIFT")) {
return "gift-" + cents;
}
// a third type means editing this method
throw new IllegalArgumentException("unknown payment type " + paymentType);
}
}
With: every payment method implements one interface. A new method is a new class, and Checkout never changes:
interface Payment {
String charge(long cents);
}
class CardPayment implements Payment {
@Override public String charge(long cents) { return "card-" + cents; }
}
// A new method is a new class. Checkout is not edited.
class VoucherPayment implements Payment {
@Override public String charge(long cents) { return "voucher-" + cents; }
}
class Checkout {
String charge(Payment payment, long cents) {
return payment.charge(cents);
}
}
This is the Strategy pattern in its simplest form (see the strategy lesson).
L: Liskov Substitution
Anywhere a base type is used, any subtype must work without surprises. A contract is the set of promises a method makes. Here: the amount must be positive, and a transaction id comes back. Every implementation must keep these promises.
Without: this subtype rejects an amount the contract allows, and returns null instead of an id. Callers that trust Payment fail with a surprise exception or a NullPointerException:
interface Payment {
// Contract: cents must be positive. Returns a non-blank transaction id.
String charge(long cents);
}
// Without: breaks the contract in two ways.
class LimitedPayment implements Payment {
@Override public String charge(long cents) {
if (cents > 10_000) throw new IllegalArgumentException("limit is 100.00"); // stricter rule
if (cents < 100) return null; // no id comes back
return "limited-" + cents;
}
}
With: each implementation keeps the same promises. A contract test checks them against every implementation, which is how Liskov is enforced in practice:
// With: keeps exactly the same promises.
class GiftCardPayment implements Payment {
@Override public String charge(long cents) {
if (cents <= 0) throw new IllegalArgumentException("amount must be positive");
return "gift-" + cents;
}
}
class ContractCheck {
static void check(List<Payment> payments) {
for (Payment p : payments) {
if (p.charge(2_000_000).isBlank()) throw new AssertionError("blank id from " + p);
try { p.charge(0); throw new AssertionError("accepted 0: " + p); }
catch (IllegalArgumentException expected) { }
}
}
}
I: Interface Segregation
Clients should not depend on methods they do not use.
Without: one big Payment interface forces a gift card to implement refund, so it throws. The refund service accepts any Payment, so refunding a gift card compiles and fails at run time:
class Without {
interface Payment {
String charge(long cents);
void refund(String transactionId);
}
static class GiftCardPayment implements Payment {
@Override public String charge(long cents) { return "gift-" + cents; }
@Override public void refund(String transactionId) {
throw new UnsupportedOperationException("gift cards cannot be refunded");
}
}
static class RefundService {
void refund(Payment payment, String transactionId) { payment.refund(transactionId); }
}
}
With: refund is a separate small interface, and only the payments that can refund implement it:
interface Payment {
String charge(long cents);
}
interface Refundable {
void refund(String transactionId);
}
class CardPayment implements Payment, Refundable {
@Override public String charge(long cents) { return "card-" + cents; }
@Override public void refund(String transactionId) { /* call the card gateway */ }
}
class GiftCardPayment implements Payment {
@Override public String charge(long cents) { return "gift-" + cents; }
}
class RefundService {
void refund(Refundable payment, String transactionId) { payment.refund(transactionId); }
}
Now refunding a GiftCardPayment is a compile error, not a runtime surprise.
D: Dependency Inversion
High-level code (the checkout policy) should not depend on low-level code (the database, the mail server). Both depend on abstractions, and the high-level side owns the abstractions.
Without: the checkout creates its own database and mail classes, so it cannot run or be tested without them:
class CheckoutBefore {
private final MySqlOrderStore store = new MySqlOrderStore();
private final SmtpNotifier notifier = new SmtpNotifier();
void place(String orderId, String email, long cents) {
store.save(orderId, cents);
notifier.send(email, "Order " + orderId + " confirmed");
}
}
With: the checkout knows only two interfaces. Which database or mail service sits behind them is decided elsewhere:
flowchart TB
C["Checkout"] --> S["OrderStore (interface)"]
C --> N["Notifier (interface)"]
S -.-|implemented by| DB["Database, or a test fake"]
N -.-|implemented by| ML["Mail service, or a test fake"]
interface OrderStore {
void save(String orderId, long cents);
}
interface Notifier {
void send(String to, String message);
}
class Checkout {
private final OrderStore store;
private final Notifier notifier;
Checkout(OrderStore store, Notifier notifier) {
this.store = store;
this.notifier = notifier;
}
void place(String orderId, String email, long cents) {
store.save(orderId, cents);
notifier.send(email, "Order " + orderId + " confirmed");
}
}
3. Dependency Injection
Dependency injection is the technique that delivers the dependencies: the checkout does not create its store, it is given one, usually through the constructor. One place, the composition root near main, builds the real objects and wires them together:
class App {
static Checkout checkout() {
return new Checkout(new InMemoryOrderStore(), new ConsoleNotifier());
}
}
class InMemoryOrderStore implements OrderStore {
final java.util.Map<String, Long> orders = new java.util.HashMap<>();
@Override public void save(String orderId, long cents) { orders.put(orderId, cents); }
}
class ConsoleNotifier implements Notifier {
@Override public void send(String to, String message) { System.out.println(to + ": " + message); }
}
- Constructor injection is the default: the object cannot exist without its dependencies, and they can be
final. - Setter or field injection allows a half-built object and hides what a class needs. Avoid it.
- A DI container (Spring, Guice) only automates the wiring. You can wire by hand.
- A service locator (
Registry.get(Mailer.class)inside the class) looks like DI but hides dependencies again. Avoid it.
The payoff is testability. The tests replace the database and the mailer with a map and a list, in one line each.
class CheckoutTest {
private final Map<String, Long> saved = new HashMap<>();
private final List<String> sent = new ArrayList<>();
private final Checkout checkout = new Checkout(saved::put, (to, msg) -> sent.add(to + ": " + msg));
@Test void savesThenNotifies() {
checkout.place("A1", "ann@x.com", 2500);
assertEquals(Map.of("A1", 2500L), saved);
assertEquals(List.of("ann@x.com: Order A1 confirmed"), sent);
}
@Test void noEmailIsSentWhenSavingFails() {
Checkout failing = new Checkout((id, c) -> { throw new IllegalStateException("db down"); },
(to, msg) -> sent.add(msg));
assertThrows(IllegalStateException.class, () -> failing.place("A2", "bo@x.com", 500));
assertTrue(sent.isEmpty());
}
}
4. Principles Beyond SOLID
| Principle | Meaning | Common misuse |
|---|---|---|
| DRY: Don't Repeat Yourself | One piece of knowledge, one place | Merging code that looks alike but changes for different reasons |
| KISS: Keep It Simple, Stupid | Choose the simplest design that works | Clever abstractions nobody can follow |
| YAGNI: You Aren't Gonna Need It | Build only what is needed now | Interfaces and factories for things that will never vary |
| Law of Demeter | Talk to your direct collaborators, not to their internals (a.getB().getC().do() is a smell) |
Piling up wrapper methods that only forward calls |
| High cohesion, low coupling | Things that change together live together, and modules know little about each other | Treating "few classes" as the same as "low coupling" |
5. Common Pitfalls
- "Single responsibility" read as "one method". A class can have many methods but one reason to change.
- Creating dependencies inside the class (
new SmtpNotifier()in the body) or calling statics, so tests need the real thing. - An abstraction with one implementation and no reason to vary. A payment method will vary, so it earns an interface. A tax rate that never changed does not need a
TaxStrategy. Add an interface when a second implementation is real or likely. - Treating the principles as a checklist. They pull against each other, so judge the trade-off.
6. Interview Questions and Answers
- What are the four pillars of OOP? Encapsulation (protect state behind methods), abstraction (show what, hide how), inheritance (reuse by "is a") and polymorphism (one call, different behaviour).
- What is the difference between encapsulation and abstraction? Encapsulation hides data so it stays valid (
Moneyrefuses negatives). Abstraction hides complexity behind a simple interface (Payment). - Overloading or overriding? Overloading: same name, different parameters, chosen by the compiler. Overriding: a subclass replaces a method, chosen at run time by the real object.
- Association, aggregation, composition or inheritance? Association: uses. Aggregation: has a part that can live without the owner. Composition: owns a part that dies with the owner. Inheritance: is a kind of. Prefer composition, and inherit only when the child can replace the parent everywhere.
- Interface or abstract class? An interface is a role with no state, and a class can implement many. An abstract class can hold fields and shared code, but a class extends only one. Prefer an interface.
- Explain Open/Closed with an example. A new payment method is a new class that implements
Payment. The checkout is not edited. - What is a Liskov violation? A subtype that breaks what callers expect of the base type, for example by throwing "not supported".
- What is the difference between dependency inversion and dependency injection? Inversion is the design rule: depend on abstractions owned by the high-level code. Injection is the technique of handing those dependencies in from outside.