These are the notes for Low-Level Design (LLD) episode 14: the L in SOLID, the Liskov Substitution Principle (LSP). Every square is a rectangle, so Square extends Rectangle must be fine... until a method written for rectangles gets the wrong answer. From that bug we invent substitutability, behavioural subtyping, design by contract (preconditions, postconditions, class invariants) and the history constraint, meet the refused bequest smell (even inside the JDK) and fix the hierarchies so the compiler catches the mistake. Every program was run with javac Main.java && java -cp . Main (Java 21); outputs and error messages are real.
1. The real-life problem: the substitute driver
A school bus follows a fixed route: the highway, then twelve stops. Parents plan their mornings around it. One day the regular driver is sick, and the agency sends a substitute, a licensed driver. On paper, any driver will do. But this one says: "I don't do highways, and I only stop when someone asks." The route didn't change, the parents didn't change, and the kids reach school late. The substitute had the right job title, but broke the promise.
2. The rectangle-square problem
A setter is a method that changes one field (setWidth). @Override (episode 8) marks a method that replaces the parent's version.
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 { // "a square IS-A rectangle"
@Override void setWidth(int w) { this.w = w; this.h = w; }
@Override void setHeight(int h) { this.w = h; this.h = h; }
}
public class Main {
static void resize(Rectangle r) { // written and tested for rectangles
r.setWidth(5);
r.setHeight(4);
System.out.println(r.getClass().getSimpleName() + ": expected 20, got " + r.area());
}
public static void main(String[] args) {
resize(new Rectangle());
resize(new Square());
}
}
Rectangle: expected 20, got 20
Square: expected 20, got 16
Setting the height to 4 also set the width to 4. No compile error, no exception: just a wrong number inside code that was correct yesterday. (getClass().getSimpleName() prints the object's real class name.)
3. Why it broke: substitutability
resizerelies on the rectangle's promise: width and height can be changed independently.- Java only checks the type:
Square extends Rectangle, so aSquareis allowed anywhere aRectangleis (upcasting, episode 9). - Nobody checks the behaviour:
Square's setters keep a different promise.
Substitutability means a child object can stand in wherever the parent is expected, and every caller still works. "Is-a" in English is not enough; ask "behaves-like-a, for every caller?"
4. The Liskov Substitution Principle
If S is a subtype of T, then objects of type T may be replaced with objects of type S without breaking the program's desirable properties.
- A subtype is a type that extends or implements another (
Squareis a subtype ofRectangle); the other is the supertype. - Barbara Liskov first stated it in her 1987 keynote Data abstraction and hierarchy (OOPSLA '87). In 1994, Liskov and Jeannette Wing formalised it in the paper A behavioral notion of subtyping.
- Behavioural subtyping: being a subtype is about behaving like the parent, not just having the same method names.
5. Design by contract
A contract is the set of promises between a method and its callers. The courier analogy:
| Courier service | Contract term | Meaning |
|---|---|---|
| "Parcel up to 5 kg, packed" | Precondition | What must be true before the call: the caller's duty |
| "Delivered within 2 days" | Postcondition | What the method guarantees after it returns |
| "Parcel never opened" | Class invariant | A fact about the object that is always true between method calls (a rectangle's area is always w * h) |
Writing these down for every method is design by contract, an idea from Bertrand Meyer (Object-Oriented Software Construction, 1988), the same Meyer as the open-closed principle.
The subtype's rules
| # | Rule | In plain words |
|---|---|---|
| 1 | Preconditions cannot be strengthened | Demand no more from callers than the parent did |
| 2 | Postconditions cannot be weakened | Promise no less than the parent did |
| 3 | Invariants cannot be weakened | Whatever was always true of the parent stays true |
| 4 | History constraint | Don't allow state changes the parent forbids (a mutable point can't be a subtype of an immutable point) |
The courier version: a franchise may accept up to 10 kg and deliver in 1 day (weaker precondition, stronger postcondition: fine). It may never accept only 2 kg or take 5 days.
The history constraint was Liskov and Wing's addition to Meyer's rules: if callers rely on an object never changing (it is immutable, episode 6), a subclass that adds a setter breaks them, even if every single method call looks fine on its own.
A strengthened precondition, in code
class Wallet {
protected int balance = 1000;
// precondition: 0 < amount <= balance
// postcondition: balance goes down by exactly amount
void pay(int amount) {
if (amount <= 0 || amount > balance)
throw new IllegalArgumentException("Bad amount " + amount);
balance -= amount;
}
}
class KidsWallet extends Wallet {
@Override void pay(int amount) { // demands MORE than the parent
if (amount > 200) throw new IllegalStateException("Kids limit is Rs 200");
super.pay(amount);
}
}
public class Main {
static void checkout(Wallet w) { // trusts Wallet's contract
w.pay(500);
System.out.println(w.getClass().getSimpleName() + " paid 500, left " + w.balance);
}
public static void main(String[] args) {
checkout(new Wallet());
checkout(new KidsWallet());
}
}
Wallet paid 500, left 500
Exception in thread "main" java.lang.IllegalStateException: Kids limit is Rs 200
at KidsWallet.pay(Main.java:13)
at Main.checkout(Main.java:19)
at Main.main(Main.java:24)
checkout followed Wallet's contract perfectly and still crashed, because the subtype changed the contract. (A kids' wallet is a fine idea; it just shouldn't be a Wallet that callers can't trust. Make the limit part of Wallet's own contract, or give it its own type.)
A weakened postcondition, in code
class Discount {
// postcondition: result <= price
int apply(int price) { return price * 90 / 100; }
}
class FestivalDiscount extends Discount {
@Override int apply(int price) { return price * 80 / 100; } // keeps it: OK
}
class FeeDiscount extends Discount {
@Override int apply(int price) { return price + 50; } // breaks it
}
public class Main {
static void bill(Discount d, int price) {
int pay = d.apply(price);
System.out.println(d.getClass().getSimpleName() + ": " + pay + (pay <= price ? " ok" : " MORE than the price!"));
}
public static void main(String[] args) {
bill(new Discount(), 1000);
bill(new FestivalDiscount(), 1000);
bill(new FeeDiscount(), 1000);
}
}
Discount: 900 ok
FestivalDiscount: 800 ok
FeeDiscount: 1050 MORE than the price!
6. Refused bequest
A bequest is what a parent leaves its children. A refused bequest is a subclass that inherits methods but won't support them.
class Bird {
void eat() { System.out.println(getClass().getSimpleName() + " eats"); }
void fly() { System.out.println(getClass().getSimpleName() + " flies"); }
}
class Sparrow extends Bird { }
class Penguin extends Bird {
@Override void fly() { // refused bequest
throw new UnsupportedOperationException("Penguins can't fly");
}
}
public class Main {
static void migrate(Bird[] flock) {
for (Bird b : flock) { b.eat(); b.fly(); }
}
public static void main(String[] args) {
migrate(new Bird[] { new Sparrow(), new Penguin() });
}
}
Sparrow eats
Sparrow flies
Penguin eats
Exception in thread "main" java.lang.UnsupportedOperationException: Penguins can't fly
at Penguin.fly(Main.java:8)
at Main.migrate(Main.java:13)
at Main.main(Main.java:16)
Symptoms: an override that does nothing, or one that throws UnsupportedOperationException (an unchecked exception, episode 5, meaning "this operation isn't supported"). This is the UnsupportedOperationException smell. The damage spreads: every caller now needs if (!(b instanceof Penguin)), and that instanceof check is the bug report.
The smell in the JDK itself
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> a = new ArrayList<>(List.of("chai", "samosa"));
List<String> b = List.of("chai", "samosa"); // also a List
a.add("jalebi");
System.out.println(a);
b.add("jalebi");
System.out.println(b);
}
}
[chai, samosa, jalebi]
Exception in thread "main" java.lang.UnsupportedOperationException
at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:142)
at java.base/java.util.ImmutableCollections$AbstractImmutableCollection.add(ImmutableCollections.java:147)
at Main.main(Main.java:9)
List.of(...) returns an unmodifiable list (episode 5). Java's documentation marks add as an optional operation, so this is legal, but a method that takes a List can't safely call add without knowing where the list came from. Know the smell, even when the JDK does it.
7. Fixing the hierarchy
Shapes: immutable siblings
The trouble was mutable setters that the square had to change. Make shapes immutable records (episode 3) and siblings under a sealed interface (episode 8: only the listed types may implement it). Neither extends the other.
sealed interface Shape permits Rect, Sq { int area(); }
record Rect(int w, int h) implements Shape {
public int area() { return w * h; }
Rect withWidth(int nw) { return new Rect(nw, h); }
}
record Sq(int side) implements Shape {
public int area() { return side * side; }
}
public class Main {
public static void main(String[] args) {
Shape[] shapes = { new Rect(5, 4), new Sq(5), new Rect(2, 3).withWidth(5) };
int total = 0;
for (Shape s : shapes) {
System.out.println(s + " area " + s.area());
total += s.area();
}
System.out.println("total " + total);
}
}
Rect[w=5, h=4] area 20
Sq[side=5] area 25
Rect[w=5, h=3] area 15
total 60
"Changing" a width returns a new Rect (a "wither" method), so nobody's square is ever reshaped behind their back. Code that uses Shape relies only on area(), which every shape honours.
Birds: split the hierarchy
class Bird {
void eat() { System.out.println(getClass().getSimpleName() + " eats"); }
}
class FlyingBird extends Bird {
void fly() { System.out.println(getClass().getSimpleName() + " flies"); }
}
class Sparrow extends FlyingBird { }
class Penguin extends Bird {
void swim() { System.out.println("Penguin swims"); }
}
public class Main {
static void migrate(FlyingBird[] flock) {
for (FlyingBird b : flock) { b.eat(); b.fly(); }
}
public static void main(String[] args) {
migrate(new FlyingBird[] { new Sparrow() });
migrate(new FlyingBird[] { new Sparrow(), new Penguin() });
}
}
Main.java:17: error: incompatible types: Penguin cannot be converted to FlyingBird
migrate(new FlyingBird[] { new Sparrow(), new Penguin() });
^
1 error
The crash moved from run time to compile time: the wrong code can't even be written. Remove the second migrate line and the program prints Sparrow eats / Sparrow flies.
| Before (violates LSP) | After (substitutable) |
|---|---|
Square extends Rectangle with mutable setters |
Rect, Sq immutable siblings under Shape |
Penguin extends Bird, fly() throws |
Sparrow extends FlyingBird, Penguin extends Bird |
| Compiles, breaks callers at run time | Wrong use doesn't compile |
Splitting Bird into smaller types is the next principle (Interface Segregation) already peeking through.
The class diagram
+-----------+
| Bird |
| + eat() |
+-----------+
^ ^ (solid line, hollow triangle = inheritance)
+------------+ +-----------+
| FlyingBird | | Penguin |
| + fly() | | + swim() |
+------------+ +-----------+
^
+-----------+
| Sparrow |
+-----------+
Common mistakes
| Mistake | Exact message | Why | Fix |
|---|---|---|---|
Square extends Rectangle with mutable setters |
no error: Square: expected 20, got 16 |
The square changes what setHeight promises |
Immutable siblings under Shape |
Subclass adds if (amount > 200) throw ... |
IllegalStateException: Kids limit is Rs 200 |
Strengthened precondition | Demand no more than the parent |
Subclass returns price + 50 from apply |
no error: a bill bigger than the price | Weakened postcondition | Promise no less than the parent |
Penguin.fly() throws |
UnsupportedOperationException: Penguins can't fly |
Refused bequest | Split: FlyingBird |
if (b instanceof Penguin) skip; in callers |
no error: a patch in every caller | Hides the broken hierarchy | Fix the types instead |
Mini project
The homework: design cars without a refused bequest. ElectricCar charges, PetrolCar refuels, and both drive. A trip method needs only driving; a fuelStation method needs only refuelling. Make passing an ElectricCar to fuelStation a compile error.
Solution
interface Car { String name(); default void drive(int km) { System.out.println(name() + " drives " + km + " km"); } }
interface Refuelable { void refuel(int litres); }
interface Chargeable { void charge(int minutes); }
class PetrolCar implements Car, Refuelable {
public String name() { return "PetrolCar"; }
public void refuel(int litres) { System.out.println(name() + " +" + litres + " L"); }
}
class ElectricCar implements Car, Chargeable {
public String name() { return "ElectricCar"; }
public void charge(int minutes) { System.out.println(name() + " charging " + minutes + " min"); }
}
public class Main {
static void trip(Car c) { c.drive(120); }
static void fuelStation(Refuelable r) { r.refuel(30); }
public static void main(String[] args) {
PetrolCar p = new PetrolCar();
ElectricCar e = new ElectricCar();
trip(p);
trip(e);
fuelStation(p);
e.charge(45);
}
}
Output:
PetrolCar drives 120 km
ElectricCar drives 120 km
PetrolCar +30 L
ElectricCar charging 45 min
fuelStation(e) would fail with incompatible types: ElectricCar cannot be converted to Refuelable. No class has a method it must refuse.
Practice
- Make
Rectangleimmutable (final fields, no setters,withWidth/withHeightreturning new objects). CanSquarestill breakresize?
Solution
No. With no setters, resize must be written as r = r.withWidth(5).withHeight(4), returning new objects; a square's "withWidth" can return a plain rectangle (new Rect(5, side)), so nothing a caller relies on is broken. The violation came from mutation: immutability removes the promise the square couldn't keep (this is also why the history constraint matters).
- Which rule does each subclass break? (a)
Wallet.payaccepts 1 to balance;GiftWallet.payaccepts only multiples of 100. (b)Sorter.sortreturns a sorted list;FastSorter.sortreturns it "mostly sorted". (c)ImmutableMoneynever changes;MutableMoney extends ImmutableMoneyaddssetAmount.
Solution
(a) Strengthened precondition. (b) Weakened postcondition. (c) History constraint: callers that relied on the value never changing are broken.
- Is this an LSP violation?
class LoggingWallet extends Wallet { @Override void pay(int a) { System.out.println("pay " + a); super.pay(a); } }
Solution
No. It demands nothing more and promises everything the parent does; logging is an extra side effect callers don't rely on. Adding behaviour is fine; changing the contract isn't.
- You receive a
List<String>parameter and need to add to it. How do you stay safe?
Solution
Don't assume it's modifiable. Either copy it (new ArrayList<>(list)) and add to the copy, or make the contract explicit in the method's name and documentation ("the caller must pass a modifiable list"). Returning a new list is usually the cleanest.
Quick quiz
class Discount {
// promise: result <= price
int apply(int price) { return price * 90 / 100; }
}
// Which subclass breaks the contract?
- A.
applyreturnsprice * 80 / 100 - B.
applyreturnsprice(no discount) - C.
applyreturnsprice + 50("service fee") - D.
applyalso logs the price
Answer
C. It weakens the postcondition: the result can be more than the price (see the FeeDiscount program above: 1050 MORE than the price!). A gives a bigger discount, B none, D adds logging; all three keep "result ≤ price".
Interview questions
- State the Liskov Substitution Principle. Objects of a supertype must be replaceable by objects of any subtype without breaking the program (Barbara Liskov, 1987; formalised with Jeannette Wing, 1994).
- Why is
Square extends Rectanglea violation?Rectangle's setters promise independent width and height;Squaremust change both, so code likesetWidth(5); setHeight(4); area() == 20fails. - What are preconditions, postconditions and invariants? What must hold before a call (caller's duty), what the method guarantees after it, and what is always true of the object between calls.
- State the contract rules for subtypes. Preconditions can't be strengthened, postconditions can't be weakened, invariants can't be weakened, and the history constraint: no state changes the parent forbids.
- What is design by contract? Bertrand Meyer's method (1988) of specifying pre/postconditions and invariants for every method.
- What is a refused bequest? A subclass that inherits methods it won't support: empty overrides or
UnsupportedOperationException. - Does the JDK violate LSP anywhere?
List.of(...)returns aListwhoseaddthrowsUnsupportedOperationException; Java documentsaddas an "optional operation". - How do you fix LSP violations? Make types immutable, make the classes siblings under a smaller shared type, or split the hierarchy (
FlyingBird), so wrong use is a compile error. - Why are
instanceofchecks before calling a parent method a smell? They patch every caller around a subtype that isn't substitutable; fix the hierarchy instead. - How does LSP relate to OCP? OCP relies on plugging in new subtypes behind an interface; that only works if every subtype honours the interface's contract (LSP).
Glossary
| Term | Meaning, with an example |
|---|---|
| Liskov Substitution Principle (LSP) | Any subtype must work wherever its supertype is expected |
| Subtype / supertype | A type that extends or implements another / the type it extends. Square / Rectangle |
| Substitutability | A child object can stand in for its parent and every caller still works |
| Behavioural subtyping | Being a subtype means behaving like the parent, not just having its methods |
| Setter | A method that changes one field. setWidth(int w) |
| Upcasting | Using a subclass object through a parent type (episode 9). Rectangle r = new Square() |
| Rectangle-square problem | Square extends Rectangle breaks code relying on independent sides |
| Contract | The promises between a method and its callers |
| Design by contract | Specifying pre/postconditions and invariants (Meyer, 1988) |
| Precondition | What must be true before a call. 0 < amount <= balance |
| Postcondition | What a method guarantees after it returns. result <= price |
| Class invariant | A fact always true of an object between calls. area == w * h |
| History constraint | A subtype may not allow state changes the parent forbids |
| Immutable | Can't change after creation (episode 6). Records, String |
| Refused bequest | A subclass inherits methods it won't support |
| UnsupportedOperationException | Unchecked exception: "this operation isn't supported" |
| UnsupportedOperationException smell | Overrides that throw it: a sign of a refused bequest |
| Optional operation | A Collection method an implementation may refuse (e.g. add on List.of) |
| Unmodifiable list | A list whose add/remove throw. List.of("chai") |
| Sealed interface | Only the listed types may implement it (episode 8). sealed interface Shape permits Rect, Sq |
| Record | A compact immutable data class. record Rect(int w, int h) |
| Wither method | Returns a copy with one field changed. withWidth(5) |
instanceof |
Checks an object's runtime type (episode 9) |
| IllegalStateException | Unchecked exception: the object isn't in a state to do this |
Summary
- LSP: wherever the parent is expected, any subtype must work (Liskov, 1987; Liskov & Wing, 1994).
Square extends Rectanglecompiles but givesexpected 20, got 16: "is-a" isn't enough; it must behave like one.- Design by contract: preconditions, postconditions, invariants (Meyer, 1988).
- Subtypes demand no more, promise no less, keep invariants, and obey the history constraint.
- Refused bequest (
UnsupportedOperationException) is the classic smell, even inList.of. - Fix the hierarchy, not the callers: immutable siblings, split types, so wrong use doesn't compile.
Next episode: SOLID 4: The Interface Segregation Principle: fat interfaces, role interfaces, and the Xerox story.