What can polymorphism do that inheritance can't?
The real advantages of Polymorphism can be seen at runtime rather than compile time. Polymorphism allows you to substitute one implementation for another without the need to change the code that uses it. Let's take your example of the Animal
hierarchy. Let's say you have a Vet
that knows how to perform health checkups on any animal (Yup he's a supervet).
class Vet {
private Animal animal;
public Vet(Animal animal) {
this.animal = animal;
}
public void perfromCheckup() {
animal.talk();
animal.poop();
}
}
You can now say :
Vet vetWithBird = new Vet(new Bird());
Vet vetWithDog = new Vet(new Dog());
vetWithBird.performCheckup();
vetWithDog.performCheckup();
Notice how you can tell the Vet
to perform a checkup on a Bird
or a Dog
or any other animal for that matter without needing to change your Vet
class. At runtime, the Dog
would bark when it goes for a checkup and the Bird
would tweet when it goes for a checkup. Imagine if instead of Animal
, the Vet
had a Bird
reference :
class Vet {
private Bird bird;
public Vet(Bird bird) {
this.bird = bird;
}
public void perfromCheckup() {
bird.talk();
bird.poop();
}
}
The poor Vet
is now only going to be able to work with a Bird
. Tell your Vet
to work with a Dog
and he will reject this right away.
Vet vetWithBird = new Vet(new Bird()); //Works fine. Vet likes birds.
Vet vet = new Vet(new Dog())// compilation error. Sorry I don't like dogs.
In summary, Polymorphism allows you to substitute subclass instances where a super-class reference is used. Inheritance allows you to inherit code from a parent class and possibly redefine that behavior in subclasses so that your code can take advantage of it at runtime through Polymorphism