lundi 6 février 2017

What can polymorphism do that inheritance can't?

Reviewing some concepts and trying to wrap my head around this.

Imagine that we have a class Animal that extends to three other classes: Dog, Cat, Bird.

This animal class has a talk() and move() function. The talk function outputs "Animal talking" and the move function outputs "Animal moving".

For a dog, this is "Dog moving" and "Dog eating". For the Cat and Bird class, this difference is paralleled "Cat moving" etc.

Now, because of polymorphism, if I do

Animal charlietheBird = new Bird()

and then call in

charlietheBird.talk()

it will output

Bird talking

because the output is determined at runtime since the compiler knows that charlie is a type of Animal of the class Bird.

HOWEVER!!

I can simply do

Bird charlietheBird = new Bird();

and then calling charlietheBird.poop(); will give the same output, because the method would have been overridden.

Aucun commentaire:

Enregistrer un commentaire