Liskov Substitution: a subtype must keep the promise
Any Bird can replace another wherever a Bird is expected — because every Bird keeps the one promise Bird makes.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
Liskov Substitution says: anywhere a Bird is expected, any subtype of Bird should work correctly. Announce only relies on Sound(), and both Sparrow and Penguin honor that promise, so either can be substituted freely.
Code
static void Announce(Bird bird) =>
Console.WriteLine(bird.Sound());
Bird bird = new Penguin();
Announce(bird);
abstract class Bird {
public abstract string Sound();
}
class Sparrow : Bird {
public override string Sound() => "Tweet";
}
class Penguin : Bird {
public override string Sound() => "Honk";
}abstract class Bird {
abstract String sound();
}
class Sparrow extends Bird {
@Override String sound() { return "Tweet"; }
}
class Penguin extends Bird {
@Override String sound() { return "Honk"; }
}
class Main {
static void announce(Bird bird) {
System.out.println(bird.sound());
}
public static void main(String[] args) {
Bird bird = new Penguin();
announce(bird);
}
}class Bird {
public:
virtual string sound() const = 0;
virtual ~Bird() = default;
};
class Sparrow : public Bird {
public:
string sound() const override { return "Tweet"; }
};
class Penguin : public Bird {
public:
string sound() const override { return "Honk"; }
};
void announce(const Bird& bird) { cout << bird.sound() << "\n"; }
int main() {
Penguin penguin; Bird& bird = penguin;
announce(bird);
}from abc import ABC, abstractmethod
class Bird(ABC):
@abstractmethod
def sound(self) -> str: ...
class Sparrow(Bird):
def sound(self) -> str: return "Tweet"
class Penguin(Bird):
def sound(self) -> str: return "Honk"
def announce(bird: Bird) -> None: print(bird.sound())
bird: Bird = Penguin()
announce(bird)Tips
- The classic trap is adding Fly() to Bird. Penguin cannot really fly, so forcing it to implement Fly() breaks the promise Bird makes — callers that expect every Bird to fly would get wrong behavior from a Penguin.
- Keep a base type’s promise to only what every subtype can genuinely deliver. A capability not every subtype has (like flying) belongs on its own smaller type instead.
In the .NET library
The name honors Barbara Liskov. Here Bird only promises Sound(), which every bird can do, so substitution is always safe — there is no Fly() to break the promise.