LOW-LEVEL DESIGN · SOLID PRINCIPLES · L · 10 OF 48

Liskov Substitution Principle in Java: Keep the Parent's Promises

The L in SOLID, shown with notification channels: an SMS sender that rejects long messages and a push sender that silently drops them both break code that trusts the Notifier interface. Learn contracts, why subtypes cannot demand more or promise less, the rules on invariants and exceptions, two ways to fix a broken subtype, and how to spot violations in interviews.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 18

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 147 lines, with a small main() demo. Save it as LiskovSubstitutionDemo.java, then run javac LiskovSubstitutionDemo.java && java LiskovSubstitutionDemo.

import java.util.ArrayList;
import java.util.List;

/** Liskov substitution: two subtypes that break the Notifier contract, then two that keep it. */
public class LiskovSubstitutionDemo {

    static final String SUMMARY = "Order 7731 is confirmed: two ceramic mugs and one teapot,"
            + " paid 1840 rupees by UPI. It arrives on Thursday between 10 am and 1 pm."
            + " Track it in the app or reply HELP. Thank you for shopping with us!";

    public static void main(String[] args) {
        System.out.println("Summary length: " + SUMMARY.length() + " characters");

        System.out.println("--- Before: subtypes that break the contract ---");
        new OrderAlerts(List.of(new EmailNotifier(), new StrictSmsNotifier(), new DropPushNotifier(false)))
                .broadcast(SUMMARY);

        System.out.println();
        System.out.println("--- After: every subtype keeps the promise ---");
        QueuedPushNotifier push = new QueuedPushNotifier(false);
        new OrderAlerts(List.of(new EmailNotifier(), new SplittingSmsNotifier(), push)).broadcast(SUMMARY);
        push.deviceCameOnline();
    }
}

enum Status { SENT, QUEUED }

record Receipt(String channel, int parts, Status status) { }

/**
 * Contract.
 * Needs: text of 1 to 1000 characters.
 * Gives: a non-null Receipt; the message is sent now or queued, never silently lost.
 */
interface Notifier {
    Receipt send(String text);
}

/** The client. It only knows the Notifier contract. */
class OrderAlerts {
    private final List<Notifier> channels;

    OrderAlerts(List<Notifier> channels) {
        this.channels = List.copyOf(channels);
    }

    void broadcast(String text) {
        for (Notifier channel : channels) {
            String name = channel.getClass().getSimpleName();
            try {
                Receipt r = channel.send(text);
                System.out.println("  " + name + " -> " + r.status() + ", " + r.parts() + " part(s)");
            } catch (RuntimeException e) {
                // Caught only so the demo can show every failure. Callers should not need this.
                System.out.println("  " + name + " -> BROKE: " + e.getClass().getSimpleName());
            }
        }
    }
}

class EmailNotifier implements Notifier {
    @Override
    public Receipt send(String text) {
        return new Receipt("email", 1, Status.SENT);
    }
}

// ---------------------------------------------------------------
// BEFORE: two subtypes that compile fine but break callers.
// ---------------------------------------------------------------

/** Stronger precondition: rejects text the parent contract allows. */
class StrictSmsNotifier implements Notifier {
    @Override
    public Receipt send(String text) {
        if (text.length() > 160) {
            throw new IllegalArgumentException("SMS max is 160 chars");
        }
        return new Receipt("sms", 1, Status.SENT);
    }
}

/** Weaker postcondition: returns null and loses the message when offline. */
class DropPushNotifier implements Notifier {
    private final boolean deviceOnline;

    DropPushNotifier(boolean deviceOnline) {
        this.deviceOnline = deviceOnline;
    }

    @Override
    public Receipt send(String text) {
        if (!deviceOnline) {
            return null; // the message is gone and nobody is told
        }
        return new Receipt("push", 1, Status.SENT);
    }
}

// ---------------------------------------------------------------
// AFTER: the same channels, now keeping every promise.
// ---------------------------------------------------------------

/** Accepts any valid text by splitting it into 160-character parts. */
class SplittingSmsNotifier implements Notifier {
    private static final int PART = 160;

    @Override
    public Receipt send(String text) {
        int parts = (text.length() + PART - 1) / PART;
        for (int i = 0; i < parts; i++) {
            String piece = text.substring(i * PART, Math.min(text.length(), (i + 1) * PART));
            sendPart(piece);
        }
        return new Receipt("sms", parts, Status.SENT);
    }

    private void sendPart(String piece) {
        // A real SMS gateway call would go here; each piece fits in one SMS.
        System.out.println("    sms part: " + piece.length() + " chars");
    }
}

/** Never loses a message: queues it while the device is offline. */
class QueuedPushNotifier implements Notifier {
    private final List<String> pending = new ArrayList<>();
    private boolean deviceOnline;

    QueuedPushNotifier(boolean deviceOnline) {
        this.deviceOnline = deviceOnline;
    }

    @Override
    public Receipt send(String text) {
        if (!deviceOnline) {
            pending.add(text);
            return new Receipt("push", 1, Status.QUEUED);
        }
        return new Receipt("push", 1, Status.SENT);
    }

    void deviceCameOnline() {
        deviceOnline = true;
        System.out.println("  device online: delivering " + pending.size() + " queued push message(s)");
        pending.clear();
    }
}

Notes

The setup

Here is the setup. A notifier interface has one method, send. Its contract says what it needs and what it gives. It needs text between one and one thousand characters. It gives back a receipt that is never null, and it promises the message is either sent now or queued, never silently lost. Order alerts holds a list of notifiers and sends an order summary of about two hundred characters to each one.

The Notifier contract
interface Notifier {
  // needs: text of 1 to 1000 chars
  // gives: a non-null Receipt;
  //   the message is sent now or
  //   queued, never silently lost
  Receipt send(String text);
}

record Receipt(String channel,
    int parts, Status status) { }

A broken subtype

Now an SMS channel is added. A single SMS holds one hundred and sixty characters, so the developer makes send throw an exception for anything longer. It compiles, it implements the interface, and its own tests pass with short messages. But order alerts sends two hundred characters, which the contract allows, and the SMS channel blows up. The caller did nothing wrong.

StrictSmsNotifier
public Receipt send(String text) {
  if (text.length() > 160)
    throw new IllegalArgumentException(
        "SMS max is 160 chars");
  return new Receipt("sms", 1, SENT);
}

Why it hurts

The usual reaction makes things worse. Someone adds a check in order alerts: if this notifier is the SMS one and the text is long, cut it first. Now the caller knows about a concrete class, the same check gets copied into every other caller, and the next channel with a limit needs another branch. The interface was supposed to hide these differences. A subtype that breaks the contract turns polymorphism back into a pile of if statements.

The hack that follows
for (Notifier n : channels) {
  if (n instanceof StrictSmsNotifier
      && text.length() > 160) {
    n.send(text.substring(0, 160));
  } else {
    n.send(text);
  }
}

every caller now knows about SMS

The idea

The principle says: if code works correctly with a type, it must keep working correctly when you pass any subtype instead. Notice that this is not about compiling. The compiler happily accepted the SMS class. It is about behaviour. A subtype must keep every promise the parent makes, so that callers never need to know which subtype they have.

The principle
  • if code works correctly with
  • a type, it must still work
  • correctly when you pass any
  • of its subtypes instead
  • not about what compiles
  • about behaviour: a subtype
  • must keep every promise
  • the parent makes

Contracts

To reason about this, think of every method as a contract with three parts. The precondition is what the caller must make true before calling, like text of one to one thousand characters. The postcondition is what the method guarantees afterwards, like a non null receipt and no lost message. An invariant is something that is always true about the object, like a sent count that never goes down.

Three parts of a contract
  • precondition: what must be
  • true before the call
  • (text is 1 to 1000 chars)
  • postcondition: what is true
  • after the call
  • (non-null receipt, not lost)
  • invariant: what is always
  • true about the object
  • (a sent count never drops)

Rule 1: ask no more

The first rule: a subtype may not demand more than the parent. The parent accepts one to one thousand characters. A subtype that accepts up to five thousand is fine, because every caller that respected the parent still works. A subtype that accepts only one hundred and sixty is broken, because it rejects calls the parent promised to handle. That is exactly the SMS bug.

Preconditions
  • parent accepts: 1 to 1000
  • subtype accepts 1 to 5000:
  • fine, it is more relaxed
  • subtype accepts 1 to 160:
  • broken, it is stricter
  • a subtype may not demand
  • more than the parent did

Rule 2: promise no less

The second rule is the mirror: a subtype may not promise less. A push channel returns null when the phone is offline and simply drops the message. The parent promised a non null receipt and no lost messages. So the caller crashes with a null pointer exception, or worse, the customer never hears about the order and nobody knows. Promising more is fine. Promising less breaks callers.

DropPushNotifier
public Receipt send(String text) {
  if (!deviceOnline)
    return null; // message lost
  return new Receipt("push", 1, SENT);
}

caller reads receipt.status():
  NullPointerException

More rules

A few more rules complete the checklist. Keep every invariant the parent has. Do not throw new kinds of exceptions that callers have no reason to expect. Do not allow state changes the parent never allowed, such as a subtype of an immutable type that can be modified. Keep the same meaning for return values. And never override a method with an empty body just to make it do nothing.

The rest of the checklist
  • keep the parent's invariants
  • no new kinds of exception
  • the caller cannot expect
  • no state changes the parent
  • never allowed (a read-only
  • type that becomes writable)
  • same meaning for return values
  • do not ignore the call with
  • an empty override

Fix 1: keep the promise

The first fix is to make the subtype keep the promise. The splitting SMS notifier accepts any text the contract allows and cuts it into parts of one hundred and sixty characters. A two hundred character summary becomes two parts. The receipt reports how many parts were sent, which is extra information, and that is allowed. The caller needs no special check.

SplittingSmsNotifier
public Receipt send(String text) {
  int parts = (text.length() + 159)
      / 160;
  for (int i = 0; i < parts; i++)
    gateway.sendPart(slice(text, i));
  return new Receipt("sms", parts, SENT);
}

200 chars: 2 parts, no exception

Fix 2: never lose it

The push channel is fixed the same way. When the phone is offline, it stores the message in a pending queue and returns a receipt with the status queued. When the phone comes back online, it sends everything in the queue. The parent contract said sent now or queued, never lost, and this class keeps exactly that promise.

QueuedPushNotifier
public Receipt send(String text) {
  if (!deviceOnline) {
    pending.add(text);
    return new Receipt("push", 1,
        QUEUED);
  }
  return new Receipt("push", 1, SENT);
}
void deviceCameOnline() { flush }

Run-through

Run the same order alerts loop again with no special cases. Email sends the summary in one part. SMS splits it and sends two parts. Push sees the phone is offline and returns queued. Every channel returns a real receipt, nothing throws, nothing is lost, and order alerts never asks which class it is talking to. That is substitutability.

Fix 3: change the shape

Sometimes a subtype truly cannot keep the promise. Then change the design, not the caller. Either make the parent contract honest, for example a max length method that every caller must respect, or stop inheriting and use a separate interface or composition. In real life an SMS is a kind of notification, but in code, is a only counts if the behaviour matches.

When you cannot keep it
  • option A: make the parent
  • contract honest, e.g. add
  • maxLength() that every
  • caller must respect
  • option B: do not inherit;
  • use a separate interface
  • or composition
  • "is a" in real life is not
  • enough; behaviour decides

How to spot it

How do you spot a violation? Instance of checks in callers are the loudest signal. So are overrides that throw unsupported operation exception, overrides with empty bodies, and comments that say do not call this method on that subtype. A great test is to run the parent's test suite against every subtype. If a subtype fails a test written for the parent, it breaks the contract.

Warning signs
  • instanceof checks in callers
  • overrides that throw
  • UnsupportedOperationException
  • empty overrides that do
  • nothing
  • docs that say "do not call
  • this on subtype X"
  • tests for the parent that
  • fail for a subtype

Where you see it

Java itself has a famous case. Timestamp extends date, but its own documentation says not to treat a timestamp as a date, because its equals method is not symmetric with the date version. The list interface takes another approach: add is documented as an optional operation, so an unmodifiable list may throw. That keeps the rule, technically, by weakening the parent contract, and it still surprises people.

In Java
  • java.sql.Timestamp extends
  • java.util.Date, yet its docs
  • say not to treat it as a
  • Date; equals is not
  • symmetric with Date
  • List.add is an "optional
  • operation": unmodifiable
  • lists throw on add, so
  • the contract warns you

Related ideas

This principle holds the others together. The open closed principle only works if new classes behave like the interface promises. Composition over inheritance often avoids the problem, because there is no subtype to break the contract. Interface segregation helps too, since a small contract is easier to keep. And design by contract is the formal version of these precondition and postcondition rules.

How it relates
  • open/closed: new classes plug
  • in safely only if they keep
  • the contract
  • composition over inheritance:
  • no subtype, no broken promise
  • interface segregation: small
  • contracts are easier to keep
  • design by contract: the formal
  • version of these rules

In LLD interviews

In LLD interviews, check each subclass against what its parent promises. Can every payment method handle every valid amount, or does one throw for small payments? Does an express elevator that skips floors still honour the elevator contract when someone requests floor three? The common mistake is inheriting only to reuse code. If the child cannot keep the parent's promises, use composition instead.

Where it comes up
  • parking lot: every Vehicle
  • must fit the spot it asks for
  • payments: every method must
  • return a result, not throw
  • for valid amounts
  • elevator: an express car that
  • skips floors breaks Elevator
  • mistake: inheritance just to
  • reuse code

Interview questions

What is the Liskov substitution principle?

If code works correctly with a base type, it must keep working correctly when given any of its subtypes. A subtype has to honour the behaviour the parent promises, not just its method signatures.

What does it mean that preconditions cannot be strengthened?

A subtype may not require more from the caller than the parent did. If the parent accepts any text up to 1000 characters, a subtype that rejects anything over 160 breaks callers that followed the parent contract.

What does it mean that postconditions cannot be weakened?

A subtype must guarantee at least what the parent guarantees. If the parent promises a non-null result and no lost messages, a subtype that returns null or silently drops work breaks callers that rely on that promise.

How can you detect a Liskov violation in code?

Look for instanceof checks in callers, overrides that throw UnsupportedOperationException, empty overrides, and documentation that says not to call some method on a certain subtype. Running the parent test suite against each subtype is a practical check.

If a subclass compiles and implements every method, can it still violate LSP?

Yes. The compiler only checks signatures. LSP is about behaviour: accepted inputs, guaranteed outputs, exceptions and invariants. A class can type-check perfectly and still surprise every caller.

How do you fix a subtype that breaks the parent contract?

Either change the subtype so it keeps the promise, change the parent contract so it is honest for all implementations, or remove the inheritance and use a separate interface or composition. Adding type checks in callers is not a fix.

What is the history constraint in LSP?

A subtype should not allow state changes that the parent type does not allow. For example, a mutable subtype of a type that promises to be immutable breaks code that relies on the value never changing.

How is LSP related to the open/closed principle?

Open/closed relies on plugging new subtypes into stable code. That only works if each new subtype behaves the way the abstraction promises; a subtype that breaks the contract forces edits back into the supposedly closed code.