Polymorphism

Polymorphism roughly means different forms. But what does it mean to us?

In the simplest words possible, any subclass can be used as a part of the code that uses the superclass.

For example, if we have an array of animals, we could put any object that is of a type that is a subclass of Animal in the Animal array, perhaps cats and dogs.

This means that we can write code that is simpler and easier to understand and modify:

//This code assumes we have an Animal class //And we have a Cat and Dog class that extends Animal Animal myAnimal = new Animal(); Dog myDog = new Dog(); Cat myCat = new Cat(); Animal [] myAnimals = new Animal[10]; myAnimals[0] = myAnimal;//As expected myAnimals[1] = myDog;//This is OK too myAnimals[2] = myCat;//And this ...

Get Android Game Programming: A Developer’s Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.