Imagine you rent a car. The agency promises "a car", and you get a model you have never driven. You still expect the brake pedal to slow it down and the steering wheel to turn it. If this particular car accelerated when you pressed the brake, it would technically still be "a car", but you would crash.
In OOP, a subclass object can be used anywhere its parent type is expected. That is how polymorphism works, and the Open/Closed Principle from the previous chapter depends on it completely. The Liskov Substitution Principle (LSP), the L in SOLID, says that this substitution must be safe: the subclass must keep the promises the parent made.
The Principle
The idea was presented by Barbara Liskov in a 1987 conference keynote, "Data Abstraction and Hierarchy". Her substitution property, in plain words:
If S is a subtype of T, then objects of type T in a program may be replaced with objects of type S without changing any of the desirable properties of that program.
Liskov and Jeannette Wing gave a more formal version in 1994:
Let φ(x) be a property provable about objects x of type T. Then φ(y) should be true for objects y of type S, where S is a subtype of T.
In everyday terms: code written against the parent type must keep working correctly, without knowing or checking which subclass it actually got.
The key insight is that LSP is about behavior, not syntax. The Java compiler already checks that a subclass has the right method names and types. It cannot check that the methods behave the way callers expect. That is the programmer's job, and LSP is the rule for it.
In the Inheritance chapter we used the "IS-A" test to decide whether inheritance fits. LSP sharpens that test: "IS-A" must mean "behaves like a", not just "is classified as a" in the real world.
The Classic Violation: Square Extends Rectangle
In geometry, every square is a rectangle. So it seems natural to write class Square extends Rectangle. Let us see what happens.
class Rectangle {
protected int width;
protected int height;
void setWidth(int w) { width = w; }
void setHeight(int h) { height = h; }
int area() { return width * height; }
}
// "A square IS-A rectangle" ... mathematically
class Square extends Rectangle {
@Override
void setWidth(int w) { width = w; height = w; } // keep sides equal
@Override
void setHeight(int h) { width = h; height = h; }
}
public class RectangleDemo {
// Written by someone who only knows about Rectangle
static void resize(Rectangle r) {
r.setWidth(5);
r.setHeight(4);
int area = r.area();
System.out.println(r.getClass().getSimpleName() + ": expected 20, got " + area
+ (area == 20 ? " OK" : " BROKEN"));
}
public static void main(String[] args) {
resize(new Rectangle());
resize(new Square());
}
}Output:
Rectangle: expected 20, got 20 OK
Square: expected 20, got 16 BROKENStep by step for the Square:
setWidth(5)sets width = 5 and height = 5.setHeight(4)sets width = 4 and height = 4.area()returns 4 × 4 = 16, not 20.
The author of resize() relied on a perfectly reasonable property of rectangles:
Setting the height does not change the width.
Square breaks that property. Each class looks correct on its own; the bug appears only when a Square is substituted for a Rectangle. That is why LSP violations are so dangerous: they show up far away from where they were introduced, often in code written months earlier by someone else.
Notice also that you cannot "fix" this inside Square. If Square.setWidth changed only the width, it would no longer be a square. The hierarchy itself is wrong for mutable rectangles.
Fixing the Design
There are two common fixes. Either make the shapes immutable, so there are no setters whose promises could be broken, or stop making one inherit from the other and give them a common abstraction that promises only what both can honor.
import java.util.List;
interface Shape {
double area();
}
// Immutable: no setters that could break a subtype's rules
final class Rectangle implements Shape {
private final double width, height;
Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
Rectangle withWidth(double w) { return new Rectangle(w, height); }
public double area() { return width * height; }
@Override
public String toString() { return "Rectangle " + width + "x" + height; }
}
final class Square implements Shape {
private final double side;
Square(double side) { this.side = side; }
public double area() { return side * side; }
@Override
public String toString() { return "Square " + side; }
}
public class ShapeDemo {
static double totalArea(List<Shape> shapes) {
double total = 0;
for (Shape s : shapes) total += s.area(); // works for ANY Shape
return total;
}
public static void main(String[] args) {
Rectangle r = new Rectangle(5, 4);
List<Shape> shapes = List.of(r, new Square(3), r.withWidth(10));
for (Shape s : shapes) System.out.println(s + " -> area " + s.area());
System.out.println("Total area = " + totalArea(shapes));
}
}Output:
Rectangle 5.0x4.0 -> area 20.0
Square 3.0 -> area 9.0
Rectangle 10.0x4.0 -> area 40.0
Total area = 69.0The Shape interface promises only "I can tell you my area". Both classes keep that promise, so totalArea() works for every shape, including ones added later. (In fact, if Rectangle were immutable, even Square extends Rectangle would satisfy LSP, because no caller could ever try to change one side independently. The violation came from mutation.)
Design by Contract: The Behavioral Rules
A method's "promises" can be described as a contract (an idea from Bertrand Meyer's Design by Contract):
Precondition: what must be true before calling the method (the caller's obligation).
Postcondition: what the method guarantees after it finishes (the method's obligation).
Invariant: what is always true about the object between method calls.
LSP translates into these rules for an overriding method:
Rule | Meaning | Memory hook |
|---|---|---|
Preconditions cannot be strengthened | The subclass must accept at least every input the parent accepts | Demand no more |
Postconditions cannot be weakened | The subclass must guarantee at least everything the parent guarantees | Promise no less |
Invariants must be preserved | Whatever is always true for the parent stays true for the subclass | Keep the rules |
History constraint | The subclass must not allow state changes the parent forbids (e.g. a mutable subclass of an immutable class) | No sneaky mutation |
A subclass may weaken preconditions (accept more inputs) and strengthen postconditions (guarantee more). Either way callers lose nothing.
Worked Example: Breaking and Keeping a Contract
MessageQueue.send() promises: "give me any non-null message and it will be added, so size() grows by 1". Three subclasses override it:
import java.util.ArrayList;
import java.util.List;
class MessageQueue {
protected final List<String> messages = new ArrayList<>();
/**
* Contract
* Precondition : msg is not null
* Postcondition: msg has been added; size() grows by 1
*/
void send(String msg) {
if (msg == null) throw new IllegalArgumentException("msg is null");
messages.add(msg);
}
int size() { return messages.size(); }
}
// Violation 1: STRONGER precondition (also rejects long messages)
class SmsQueue extends MessageQueue {
@Override
void send(String msg) {
if (msg == null || msg.length() > 10) {
throw new IllegalArgumentException("SMS limit is 10 chars");
}
messages.add(msg);
}
}
// Violation 2: WEAKER postcondition (silently drops duplicates)
class DedupQueue extends MessageQueue {
@Override
void send(String msg) {
if (msg == null) throw new IllegalArgumentException("msg is null");
if (!messages.contains(msg)) messages.add(msg);
}
}
// Fine: same precondition, keeps the postcondition, adds extra behaviour
class LoggingQueue extends MessageQueue {
@Override
void send(String msg) {
super.send(msg);
System.out.println(" [log] sent: " + msg);
}
}
public class ContractDemo {
// Client written against MessageQueue's documented contract
static void client(MessageQueue q) {
String name = q.getClass().getSimpleName();
try {
q.send("Exam on Monday at 10 am");
q.send("Hello");
q.send("Hello");
System.out.println(name + ": size = " + q.size()
+ (q.size() == 3 ? " OK" : " BROKEN (expected 3)"));
} catch (IllegalArgumentException e) {
System.out.println(name + ": BROKEN, threw " + e.getMessage());
}
}
public static void main(String[] args) {
client(new MessageQueue());
client(new SmsQueue());
client(new DedupQueue());
client(new LoggingQueue());
}
}Output:
MessageQueue: size = 3 OK
SmsQueue: BROKEN, threw SMS limit is 10 chars
DedupQueue: size = 2 BROKEN (expected 3)
[log] sent: Exam on Monday at 10 am
[log] sent: Hello
[log] sent: Hello
LoggingQueue: size = 3 OKSubclass | What changed | LSP? |
|---|---|---|
| Rejects valid long messages: stronger precondition | Violates |
| Sometimes does not add: weaker postcondition | Violates |
| Same precondition, same postcondition, plus extra logging | Satisfies |
Each violating class might be perfectly sensible on its own. An SMS queue really does have a length limit. The mistake is pretending it is a general MessageQueue. Better options: give it its own type, or design the base contract honestly (for example, a trySend() method that returns false when a message cannot be accepted, which every subclass can then honor).
Signature Rules (What the Compiler Checks)
LSP also has rules about method types. Java enforces some of them at compile time.
Rule | Meaning | In Java |
|---|---|---|
Return types are covariant | An override may return a more specific type | Allowed since Java 5 (e.g. |
Parameter types are contravariant | An override could, in theory, accept a more general type | Not supported: a different parameter type makes it an overload, not an override |
Exceptions | An override must not throw new kinds of exceptions callers do not expect | Enforced for checked exceptions only |
Visibility | An override must be at least as accessible | Enforced (cannot reduce |
import java.io.FileNotFoundException;
import java.io.IOException;
class Reader {
Object read() throws IOException { return "data"; }
}
class GoodReader extends Reader {
@Override
String read() throws FileNotFoundException { return "text"; } // narrower exception, covariant return: allowed
}
class BadReader extends Reader {
@Override
Object read() throws Exception { return "x"; } // broader checked exception: rejected
}Compiler output:
Overrides.java:15: error: read() in BadReader cannot override read() in Reader
Object read() throws Exception { return "x"; } // broader checked exception: rejected
^
overridden method does not throw Exception
1 errorGoodReader compiles: it returns a narrower type and throws a narrower exception, so it promises more and threatens less. BadReader is rejected, because a caller prepared only for IOException would be surprised by a general Exception. However, the compiler does not check unchecked exceptions like IllegalArgumentException or UnsupportedOperationException, which is exactly how SmsQueue slipped through.
LSP in the Java Standard Library
Even the JDK has a famous borderline case:
import java.util.ArrayList;
import java.util.List;
public class UnmodifiableDemo {
static void addDefaultSubject(List<String> subjects) {
subjects.add("Maths"); // compiles for EVERY List
}
public static void main(String[] args) {
List<String> mutable = new ArrayList<>(List.of("Physics"));
addDefaultSubject(mutable);
System.out.println("ArrayList: " + mutable);
List<String> fixed = List.of("Physics");
try {
addDefaultSubject(fixed);
} catch (UnsupportedOperationException e) {
System.out.println("List.of(): " + e.getClass().getSimpleName());
}
}
}Output:
ArrayList: [Physics, Maths]
List.of(): UnsupportedOperationExceptionaddDefaultSubject compiles for every List, but fails at run time for an unmodifiable list. Technically the List documentation marks add() as an "optional operation" that may throw UnsupportedOperationException, so the contract allows it, but it means a caller cannot fully trust a plain List parameter. Java's designers accepted this trade-off to avoid a large number of separate read-only and modifiable interfaces. Kotlin, for example, chose the other route with separate List and MutableList types. This is a good example to mention in interviews.
How to Recognise an LSP Violation
An overriding method throws
UnsupportedOperationExceptionor does nothing ("this bird cannot fly").Client code checks the actual type before using it:
if (shape instanceof Square) { ... }. If callers must know the subclass, substitution has already failed.An override adds extra validation that rejects inputs the parent accepted.
Tests written for the parent class fail when run against the subclass.
The subclass's documentation has to say "unlike the parent, this one ...".
Example: Birds and Penguins
Bad Better
──────────────────────────── ──────────────────────────────────
class Bird { void fly() } class Bird { void eat() }
class Sparrow extends Bird interface Flyer { void fly() }
class Penguin extends Bird { class Sparrow extends Bird implements Flyer
void fly() { class Penguin extends Bird
throw new (no fly() at all)
UnsupportedOperationException();
}
}With the better design, a method that needs flying takes a Flyer, and the compiler simply will not let you pass a penguin. Moving a promise into a smaller, more specific interface is closely related to the Interface Segregation Principle, covered in the next chapter.
Why LSP Matters
OCP depends on it. "Add a new subclass without changing the client" only works if the new subclass behaves correctly in the client.
It keeps polymorphism trustworthy. Without it, every call through a parent reference is a potential surprise.
It prevents
instanceofchains, which bring back the type-checking code that polymorphism was supposed to remove.It guides when not to inherit. If a subclass cannot honor the parent's contract, prefer composition or a different abstraction (recall the composition discussion in Association, Aggregation & Composition).
Common Mistakes
Using real-world classification as the only test. "A square is a rectangle" is true in geometry but false for mutable
Rectangleobjects.Thinking the compiler guarantees LSP. It checks signatures, not behavior.
Overriding a method to throw "not supported". That is almost always a sign that the hierarchy is wrong.
Mixing up the direction of the rules. Subclasses may accept more and promise more; they may not accept less or promise less.
Believing LSP forbids all overriding. Overriding to change how something is done (a different algorithm, extra logging) is fine as long as what is promised stays the same.
Interview Questions
State the Liskov Substitution Principle in one sentence.
Objects of a subclass must be usable wherever objects of the parent class are expected, without breaking the correctness of the program.
Why does Square extends Rectangle violate LSP?
A mutable Rectangle lets callers set width and height independently. Square must keep them equal, so after setWidth(5) and setHeight(4) a square has area 16 instead of the 20 a Rectangle caller expects. The subclass breaks the parent's behavioral contract.
What are the precondition and postcondition rules of LSP?
An overriding method must not strengthen preconditions (demand more from callers) and must not weaken postconditions (guarantee less). It may weaken preconditions and strengthen postconditions. Invariants of the parent must also be preserved.
Does Java's compiler enforce LSP?
Only partly: it enforces signature rules such as covariant return types, no broader checked exceptions and no reduced visibility. Behavioral rules (preconditions, postconditions, invariants, unchecked exceptions) are not checked.
Give a real Java library example related to LSP.
Unmodifiable lists such as List.of() throw UnsupportedOperationException from add(). The List contract marks add() as optional, so it is technically allowed, but code written against List cannot assume it can add elements.
How do you fix an LSP violation?
Rethink the hierarchy: make classes immutable, extract a smaller common interface that all subclasses can honor, move optional abilities into separate interfaces (e.g. Flyer), or use composition instead of inheritance.
Summary
LSP: subclasses must be substitutable for their parent without breaking correct programs.
It is about behavior; "IS-A" must mean "behaves like a".
Rules: no stronger preconditions, no weaker postconditions, preserve invariants, respect the history constraint.
Java checks the signature rules (covariant returns, checked exceptions, visibility) but not the behavioral ones.
Warning signs:
UnsupportedOperationExceptionoverrides, empty overrides,instanceofchecks in clients.Fixes: immutability, a better abstraction, smaller interfaces, or composition.
The penguin example showed that some problems come from interfaces that promise too much. In the next chapter, SOLID: Interface Segregation & Dependency Inversion, we learn how to design small, focused interfaces and how to make high-level code depend on them instead of on concrete classes.