Search code examples
oopsolid-principles

Can Liskov Substitution Principle be applied (php example)?


"Subtypes must be substitutable for their base types"

Let's say I have a Bird class already, and:

class Parrot extends Bird {
   public function Talk() {
     echo 'Talk';
   }
}

A Bird can't talk so I can't substitute a Parrot with a Bird.

This is just a basic example but usually the extended class can do much more then the base class. What am I missing?


Solution

  • The point is a parrot should act like a bird in all ways, so that someone who has a plan for dealing with birds in general won't be surprised by a parrot they run across. If the parrot happens to be able to talk as well, it doesn't matter, because their plan doesn't involve asking birds to talk.

    For example, perhaps they just call $bird->fly() on every bird they get - the ability of a parrot to talk won't disrupt that activity, so their algorithm still works. But if you invent a sort of bird that can't fly (an ostrich, say), then you've violated the principle, and their general bird-handling algorithm no longer works on all sorts of birds.