Polymorphism

We already know that polymorphism means different forms. But what does it mean to us?

Boiled down to its simplest:

Note

Any subclass can be used as part of the code that uses the superclass.

This means we can write code that is simpler and easier to understand, and easier to modify or change.

Also, we can write code for the superclass and rely on the fact that no matter how many times it is sub-classed, within certain parameters, the code will still work. Let's discuss an example.

Supposing we want to use polymorphism to help write a zoo management game. We will probably want to have a method like feed. We will probably want to pass a reference to the animal to be fed, into the feed method. This might seem like we need to write a feed method for each type of Animal.

However, we can write polymorphic methods with polymorphic return types and arguments.

Animal feed(Animal animalToFeed){
   // Feed any animal here
   return animalToFeed;
}

The method above has an Animal as a parameter which means that ANY object which is built from a class which extends Animal can be passed into it. And as you can see in the code above the method also returns an Animal which has the same benefits.

There is a small stumbling block with polymorphic return types and that is that we need to be aware of what is being returned and make it explicit in the code which calls the method.

For example, we could handle an Elephant being passed into the feed method like this:

someElephant = (Elephant) feed(someElephant);

Notice the highlighted (Elephant) in the previous code. This makes it plain that we want an Elephant from the returned Animal. This is called casting. We have already seen casting with primitive variables in Chapter 3, Variables, Operators, and Expressions.

So you can even write code today and make another subclass in a week, month, or year, and the very same methods and data structures will still work.

Also, we can enforce upon our subclasses a set of rules as to what they can and cannot do, as well as how they do it. So good design in one stage can influence it at other stages.

But will we ever really want to instantiate an actual Animal?