Lesson 5 of 12 · 10 min · Object-oriented Java

SOLID principles with small Java examples

Covers: Java 25 LTS (also valid on 21). Updated 13 Nov 2026. Part of the Java Full Stack Developer roadmap.

What you will learn

  • What each of the five SOLID principles says
  • A small bad example and a better one for each
  • How SOLID leads to dependency injection, used by Spring
  • Avoid over-engineering: when to apply them and when not
  • Answer SOLID questions in interviews

In simple words

SOLID is five rules of thumb that help you write code that is easy to change. Imagine a kitchen where one person does everything: cooking, billing, cleaning and ordering. If the billing rules change, you must disturb the whole kitchen. SOLID says: give each part one clear job, let new features be added without rewriting old code, and let parts depend on simple contracts instead of on each other's details.

Words to know

  • Responsibility: one reason for a class to change.
  • Abstraction: an interface or abstract type that hides the details.
  • Dependency: another class that your class needs to do its work.
  • Coupling: how strongly one part of the code depends on another.

S: Single Responsibility Principle

A class should have only one reason to change.

Bad: one class that validates, saves to the database and sends email:

class OrderService {
    void placeOrder(Order o) {
        if (o.amount() <= 0) throw new IllegalArgumentException();
        // ... SQL to insert the order ...
        // ... SMTP code to email the receipt ...
    }
}

It changes when validation rules change, when the database changes and when email changes. Better: separate collaborators.

class OrderService {
    private final OrderValidator validator;
    private final OrderRepository repository;
    private final ReceiptSender sender;
    // constructor sets the three fields
    void placeOrder(Order o) {
        validator.validate(o);
        repository.save(o);
        sender.send(o);
    }
}

OrderService now only coordinates. Each piece is small and easy to test. "Responsibility" means a reason to change, not "one method".

O: Open/Closed Principle

Open for extension, closed for modification.

Bad: adding a new discount type means editing a growing if/else:

double discount(String type, double amount) {
    if (type.equals("STUDENT")) return amount * 0.9;
    if (type.equals("FESTIVAL")) return amount * 0.8;
    return amount;                      // add another if for every new type
}

Better: an abstraction and one class per rule. New rules are new classes:

interface Discount { double apply(double amount); }
record StudentDiscount() implements Discount { public double apply(double a) { return a * 0.9; } }
record FestivalDiscount() implements Discount { public double apply(double a) { return a * 0.8; } }

double checkout(double amount, Discount d) { return d.apply(amount); }

The checkout code never changes when a new discount is added. In modern Java, a lambda can be the implementation, and sealed interfaces suit a closed set where you want the compiler to force you to update every switch.

L: Liskov Substitution Principle

Code that works with a base type must keep working when given any subtype.

Bad: a subtype breaks the promise of its parent:

class Bird { void fly() { /* ... */ } }
class Penguin extends Bird {
    @Override void fly() { throw new UnsupportedOperationException(); }   // surprise!
}

A method that takes a Bird and calls fly() crashes for a Penguin. The hierarchy is wrong: not every bird flies. Better: separate the capability.

interface Flyer { void fly(); }
class Sparrow implements Flyer { public void fly() { /* ... */ } }
class Penguin { /* swims, does not implement Flyer */ }

Practical rules: a subclass must not strengthen preconditions (demand more), weaken postconditions (promise less) or throw unexpected exceptions; overridden methods must respect the parent's contract. The classic example is a Square that extends Rectangle and breaks setWidth/setHeight expectations. If you find yourself throwing UnsupportedOperationException in an override, reconsider the inheritance.

I: Interface Segregation Principle

Clients should not be forced to depend on methods they do not use.

Bad: a fat interface:

interface Worker {
    void code();
    void test();
    void manageTeam();
}
class Intern implements Worker {       // must implement manageTeam() though it makes no sense
    public void code() {}
    public void test() {}
    public void manageTeam() { throw new UnsupportedOperationException(); }
}

Better: small, focused interfaces:

interface Coder { void code(); }
interface Tester { void test(); }
interface Manager { void manageTeam(); }
class Intern implements Coder, Tester { /* only what it does */ }

Callers depend only on what they use, which also makes mocks tiny. The JDK has this shape: Runnable, Comparable and AutoCloseable each have one method.

D: Dependency Inversion Principle

High-level code should depend on abstractions, not on concrete low-level classes.

Bad: the service creates its own concrete dependency:

class OrderService {
    private final MySqlOrderRepository repository = new MySqlOrderRepository();   // hard-wired
}

You cannot test it without a real MySQL, and switching to PostgreSQL means editing the service. Better: depend on an interface, and receive the implementation from outside:

interface OrderRepository { void save(Order o); }

class OrderService {
    private final OrderRepository repository;
    OrderService(OrderRepository repository) { this.repository = repository; }   // injected
}

In production you pass the JPA implementation; in a unit test you pass a fake or a mock. Passing dependencies in through the constructor is dependency injection (DI). It is the principle behind Spring: you declare what each class needs, and the Spring container creates the objects and wires them together (next course). Dependency Inversion is the principle; dependency injection is the technique; an IoC container is the tool.

SOLID in one table

Letter Principle Symptom it fixes Typical tool
S Single Responsibility a class changes for many unrelated reasons split classes by reason to change
O Open/Closed editing old code to add a new case interfaces, polymorphism, strategy
L Liskov Substitution subclasses that break the parent's contract careful hierarchies, composition
I Interface Segregation classes forced to implement unused methods small interfaces
D Dependency Inversion hard-wired concrete dependencies, untestable code interfaces, constructor injection

Do not over-apply

SOLID is guidance, not a law. A tiny script does not need five interfaces. Extra abstraction has a cost: more files and indirection. Apply a principle when you feel the pain it solves: a class that keeps changing, an if/else that keeps growing, a test that cannot run without a database. Prefer simple code now, and refactor as real needs appear. Two related rules worth knowing: DRY (do not repeat knowledge) and YAGNI (do not build what you do not need yet), and the guideline "favour composition over inheritance".

Common mistakes

  • Treating one class per method as Single Responsibility.
  • Creating an interface for every class with a single implementation and no reason.
  • Using inheritance for code reuse, breaking Liskov.
  • new everywhere for collaborators, making code untestable.
  • Reciting definitions in an interview without an example.

Try it yourself

  1. Take a method of your own that does validation, saving and notification, and split it into three collaborators.
  2. Replace an if/else chain on a type string with an interface and implementations.
  3. Find (or invent) a subclass that breaks its parent's promise, and redesign it.
  4. Pass a repository interface into a service through its constructor and write a test using a hand-made fake.
  5. Explain each of the five principles to a friend with a different example from this lesson.

Check yourself

What does the Single Responsibility Principle say?

A class should have one reason to change, so one cohesive responsibility.

How does the Open/Closed Principle help?

You add new behaviour by adding new classes that implement an abstraction, without editing the code that already works.

What is a Liskov violation?

A subclass that cannot be used wherever the parent is expected, for example it throws on an inherited method or strengthens its requirements.

What is the relationship between Dependency Inversion and dependency injection?

Dependency Inversion is the principle of depending on abstractions; dependency injection is a technique that supplies the concrete dependencies from outside, usually through the constructor.

Interview questions

Explain SOLID with examples.

Single responsibility: split validation, persistence and notification. Open/closed: add discounts as new classes implementing a Discount interface. Liskov: a Penguin must not extend a Bird whose fly() it cannot do. Interface segregation: use small interfaces instead of a fat Worker. Dependency inversion: the service depends on an OrderRepository interface passed in through its constructor.

How does SOLID relate to unit testing?

Small single-purpose classes and injected interfaces let you test each unit in isolation with fakes or mocks, without databases or networks.

When should you not apply a SOLID principle?

When it adds abstraction with no benefit, for example interfaces with one implementation that never changes in a tiny program. Apply the principles to relieve a real problem.

Summary

  • S: one reason to change; O: extend by adding code, not editing; L: subtypes honour the parent's contract; I: small interfaces; D: depend on abstractions, injected from outside.
  • Dependency injection (constructor injection) is how Dependency Inversion is done, and what Spring automates.
  • Apply SOLID to relieve real pain; avoid needless abstraction.

Going deeper

See how much of this you can explain

A free mock interview asks you new questions on Core Java: OOP, collections and exceptions for Java Full Stack Developer and scores every answer, with what to fix.