Scrivio Interview library
ConceptFoundations7 min read · updated 12 November 2026

Explain each SOLID principle in one or two sentences with a Java example.

Single responsibility: a class has one reason to change, so report formatting and data loading live in different classes. Open/closed: we add behaviour by adding implementations, such as a new DiscountPolicy, rather than editing existing code. Liskov substitution: a subtype must work wherever its supertype is expected. Interface segregation: small focused interfaces instead of large ones that force empty implementations. Dependency inversion: high-level code depends on an abstraction it owns, and the implementations are injected.

Why this question is asked

SOLID is five design principles collected by Robert C. Martin, and almost every Java interview touches them, because they explain why well-structured Spring applications look the way they do. The risk is answering with five slogans that the interviewer has heard a hundred times. A strong answer gives each principle in a sentence or two and then a small Java example that shows the problem and the fix. In this answer, we will go through the five principles in order, each with a short before-and-after example, and finish with a table that puts them side by side.

1Single Responsibility: One Reason to Change

The single responsibility principle says a class should have one reason to change, meaning it serves one kind of requirement or one group of people. A class that loads sales data and also formats it as a PDF changes when the database schema changes and also when the finance team wants a new layout. Those changes collide in one file and one test suite.

Java
// before: two reasons to change in one class
class SalesReport {
List<Sale> load(LocalDate day) { /* SQL query */ }
byte[] toPdf(List<Sale> sales) { /* layout, fonts, totals */ }
}
// after: each class changes for one reason
class SalesRepository { List<Sale> findByDay(LocalDate day) { /* SQL */ } }
class SalesPdfFormatter { byte[] format(List<Sale> sales) { /* layout */ } }
byte[] pdf = formatter.format(repository.findByDay(LocalDate.of(2026, 11, 3))); // a 2-page PDF

Now a schema change touches only SalesRepository, and a layout change touches only SalesPdfFormatter, which can be tested with a list of sales in memory and no database. Notice that the principle is about reasons to change, not about having one method: a formatter can have ten methods and still have one responsibility.

2Open/Closed: Extend Without Editing

The open/closed principle says software should be open for extension but closed for modification: we add new behaviour by adding new code, rather than editing code that already works. The usual tool is an interface with several implementations.

Java
interface DiscountPolicy { Money apply(Order order); }
class NoDiscount implements DiscountPolicy { public Money apply(Order o) { return o.total(); } }
class TenPercentOff implements DiscountPolicy {
public Money apply(Order o) { return o.total().times(new BigDecimal("0.90")); }
}
// new requirement: Black Friday. We add a class; Checkout does not change.
class BlackFridayDiscount implements DiscountPolicy {
public Money apply(Order o) { return o.total().times(new BigDecimal("0.70")); }
}
class Checkout {
private final DiscountPolicy policy;
Checkout(DiscountPolicy policy) { this.policy = policy; }
Money price(Order o) { return policy.apply(o); } // 100.00 -> 70.00 with BlackFridayDiscount
}

Without the interface, Checkout would contain a switch on discount type, and every new promotion would mean editing and retesting Checkout. With it, Checkout is closed: its code and tests are unchanged, and the new behaviour arrives as a new class. Open/closed pays off where variation is frequent; for stable, closed sets of cases a switch can be the simpler choice.

3Liskov Substitution: Subtypes Keep the Promise

The Liskov substitution principle says that if code works with a supertype, it must keep working when given any subtype. A subtype may do more, but it must not demand more from callers or deliver less than the supertype promised. The classic violation is a Square that extends Rectangle.

Java
class Rectangle {
protected int w, h;
void setWidth(int w) { this.w = w; }
void setHeight(int h) { this.h = h; }
int area() { return w * h; }
}
class Square extends Rectangle {
@Override void setWidth(int w) { this.w = w; this.h = w; }
@Override void setHeight(int h) { this.w = h; this.h = h; }
}
static int stretch(Rectangle r) { r.setWidth(5); r.setHeight(4); return r.area(); }
stretch(new Rectangle()); // 20
stretch(new Square()); // 16: the caller's expectation is broken

The stretch method was written against Rectangle's promise that width and height are independent. Square breaks that promise, so code that is correct for rectangles fails for squares. The fix is to not model Square as a mutable Rectangle at all, for example by making both immutable records implementing a Shape interface. In the JDK, a familiar example is an unmodifiable List that throws on add: callers must check the documentation, which is why APIs document such optional operations explicitly.

4Interface Segregation: Small, Focused Interfaces

The interface segregation principle says clients should not be forced to depend on methods they do not use. A large interface makes every implementation provide everything, often as empty methods or methods that throw, and every client depends on changes to methods it never calls.

Java
// before: one wide interface
interface Machine { void print(Doc d); void scan(Doc d); void fax(Doc d); }
class SimplePrinter implements Machine {
public void print(Doc d) { /* prints */ }
public void scan(Doc d) { throw new UnsupportedOperationException(); } // forced
public void fax(Doc d) { throw new UnsupportedOperationException(); } // forced
}
// after: focused roles, combined where they really exist
interface Printer { void print(Doc d); }
interface Scanner { void scan(Doc d); }
class SimplePrinter implements Printer { public void print(Doc d) { /* prints */ } }
class OfficeMachine implements Printer, Scanner { /* both, for real */ }

Now a class that only prints depends only on Printer, and a SimplePrinter cannot be handed to code that needs scanning, because the compiler stops it instead of an exception at run time. Spring Data shows the same idea: Repository, CrudRepository and ListCrudRepository let us expose only the operations we need.

5Dependency Inversion: Depend on Abstractions You Own

The dependency inversion principle says high-level policy should not depend on low-level details; both should depend on abstractions, and the abstraction belongs to the high-level side. In practice, the business service declares the interface it needs, and infrastructure implements it. Dependency injection, which Spring does for us, is how the implementation reaches the service.

Java
// owned by the domain: says what the service needs, not how
interface PaymentGateway { PaymentResult charge(Money amount, CardToken card); }
@Service
class OrderService {
private final PaymentGateway gateway; // depends on the abstraction
OrderService(PaymentGateway gateway) { this.gateway = gateway; }
void checkout(Order o) { gateway.charge(o.total(), o.card()); }
}
@Component
class StripeGateway implements PaymentGateway { /* HTTP calls to the provider */ }
new OrderService(new FakeGateway()).checkout(order); // in a test: no network, result APPROVED
SOLID at a glance
PrincipleIn one lineJava example
Single responsibilityone reason to changeSalesRepository vs SalesPdfFormatter
Open/closedextend by adding code, not editingnew DiscountPolicy implementation
Liskov substitutionsubtypes keep the supertype's promisesSquare must not break Rectangle callers
Interface segregationsmall interfaces, no forced methodsPrinter and Scanner, not Machine
Dependency inversiondepend on abstractions the policy ownsOrderService -> PaymentGateway

Notice the direction of the arrows. OrderService does not import anything from the Stripe client; StripeGateway imports the domain's interface. The infrastructure depends on the domain, not the other way round, which is the inversion. That is what lets us swap providers or test the service with a fake.

6Follow-up questions

Should every class follow every SOLID principle strictly?

No. They are guidelines that help where change actually happens. Applying them mechanically produces interfaces with one implementation, tiny classes that are hard to follow and abstractions for variation that never comes. A good habit is to apply them when a real pain appears, such as a class that keeps changing for unrelated reasons, or a switch that grows with every release.

How does Spring relate to SOLID?

Spring makes dependency inversion and open/closed cheap. Constructor injection means a class declares the abstractions it needs and Spring supplies the implementation, and adding a new bean that implements an interface, such as another DiscountPolicy collected into a List, extends behaviour without editing the code that uses the list.

7Conclusion

In this answer, we went through the five SOLID principles with Java examples: separating data loading from report formatting for single responsibility, adding a BlackFridayDiscount class without editing Checkout for open/closed, the Square that breaks Rectangle's callers for Liskov substitution, splitting a wide Machine interface into Printer and Scanner for interface segregation, and an OrderService that depends on a domain-owned PaymentGateway with an injected implementation for dependency inversion. They are guidelines to apply where change really happens, not rules to follow mechanically.

What to say in the interviewAbout 90 seconds aloud

Open with

Single responsibility means a class should have one reason to change. For example, I would not put the SQL that loads sales data and the PDF layout of a report in the same class, because the database and the finance team's layout change for different reasons; I would have a repository and a formatter.

Then, if they want more

Open/closed means I can add behaviour without editing existing code: Checkout depends on a DiscountPolicy interface, so a new Black Friday discount is a new class, and Checkout and its tests stay untouched. Liskov substitution means a subtype must work anywhere its supertype is expected.

The classic counterexample is a Square extending a mutable Rectangle: a method that sets width to 5 and height to 4 expects an area of 20, but gets 16 for a square, so Square breaks Rectangle's promise.

Interface segregation means small focused interfaces: instead of one Machine interface with print, scan and fax that forces a simple printer to throw from scan and fax, I have Printer and Scanner and implement only what is real.

Dependency inversion means high-level code depends on an abstraction it owns, and implementations are injected: OrderService depends on a PaymentGateway interface defined in the domain, and Spring injects a Stripe implementation in production or a fake in tests. I treat all five as guidelines, applied where change actually happens.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Explain each SOLID principle in one or two sentences with a Java example.": https://scrivio-interview-library.netlify.app/java/oop-principles/4466714dc5/