Arrays and ArrayLists are polymorphic
We already know that we can put objects into arrays and ArrayList
. But being polymorphic means they can handle objects of multiple distinct types as long as they have a common parent type all within the same array or ArrayList
.
In Chapter 10, Object-Oriented programming, we learned that polymorphism means different forms. But what does it mean to us in the context of arrays and ArrayList
?
Boiled down to its simplest form: any subclass can be used as part of the code that uses the super class.
For example, if we have an array of Animals,
we could put any object that is a type that is a subclass of Animal
in the Animal
array—for example, Cats
and Dogs
.
This means we can write code that is simpler and easier to understand, as well as easier to change:
// 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 ...