This is a problem I recently had to deal with.
Let's say I have a parent class Enemy
with child classes EnemyBlob
and EnemyBat
. Now lets say I want to store all of the enemies in an ArrayList. If I try to do ArrayList<EnemyBat>
then I'll need a seperate ArrayList for each type of Enemy.
However, if I use ArrayList<Enemy>
then I can add both EnemyBlob
's and EnemyBat
's to it.
In addition, this lets you use different types of objects.
ArrayList
is a subclass of List
. If you define all the places you define a list as ArrayList
s, then if you get a different type of List
(for example to a CopyOnWriteArrayList
) then you won't be able to use it.
Basically Polymorphism gives you flexibily to use and override classes.