Book Image

Learning Java by Building Android Games

By : John Horton
Book Image

Learning Java by Building Android Games

By: John Horton

Overview of this book

Table of Contents (17 chapters)
Learning Java by Building Android Games
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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 is fine as well

We can also write code for the superclass and rely on the fact that no matter how many times it is subclassed, within certain parameters, the code will still work. Let's continue our previous example:

//6 months later we need elephants...