Polymorphism can be one of the harder concepts to get your head around when first learning to code. Here’s a simple tutorial designed to introduce polymorphism using a polymorphic array to illustrate its usefulness. Hurray! As I’m learning Java right now this tutorial will be in Java and it’s going to assume that you’ve already got a basic knowledge of the language. Polymorphism is the concept of being able to handle objects of different data types using the same interface. Here’s how we’re going to do it:
The example I’m going to give will be, naturally, games-based in that we’re going to have different types of enemies that have the same interface but do different things. First we’ll write the Enemy class:
Here we have our abstract base class that defines the interface for all subclasses. Simples.
Next we have our two types of enemy that the player will face in the game; Ninjas and Pirates. As noted before both of the subclasses inherit from the Enemy base class but also override the attack function. So, why did we bother doing this? Surely it would be simpler to just define separate attack functions for both of these classes and not inherit from Enemy. Or would it?
In our game, we’re going to have many different kind of enemies on the screen and we want them to all attack at the same time. Rather than use a line of text for every time we want something to attack we’re going to create an array of enemies and use a for loop to get them all to attack at once.
In first line of our main method we declare an array with a data type of Enemy. Next we fill the elements of the enemyArray with a Ninja and a Pirate. We can do this because both Ninja and Pirate are subclasses of Enemy and this relationship is called an “is-a” relationship i.e. a Ninja is-a Enemy and a Pirate is-a Enemy.
Another consequence of inheritance is that anything a base class can do, a subclass can do, and therefore we can treat them uniformly when we want them to attack because the attack function has been defined in the base class. With that in mind we can now iterate over the enemyArray and, because a Pirate is-a Enemy and a Ninja is-a Enemy, we can call the attack function like we’ve done above to get this result:
There are some things to bear in mind when using polymorphism in this way:
Bear in mind that the aim of this is to treat a series of objects uniformly this aim will not have been achieved if functions of different subclasses take different arguments/return different things. We want to be able to guarantee that we can use the subclasses in the same way we can use the base class.
So, in summary, we created a base class which has multiple subclasses inheriting from it and placed the subclasses in a single polymorphic array. This allowed us to iterate over the array and perform actions within the program using a standardised interface. I also hope to one day write a post when I’m not completely shattered.