We can declare a variable of the superclass type to hold instances of any of the subclass types. | |
AquariumObject obj; obj = new AquaFish(aqua); ⋮ obj = new Crab(aqua); ⋮ obj = new Seahorse(aqua); |
Polymorphism
poly: many morph: shape A variable that is declared to be of an abstract or superclass type can hold an instance of any subclass (take on many shapes). We say that an instance of the subclass "is-a" member of the superclass. |
Or we could put instances of any of the subclasses in an ArrayList of the
superclass type:
ArrayList<AquariumObject> objects = new ArrayList<AquariumObject>(); objects.add(new AquaFish(aqua)); objects.add(new Crab(aqua)); objects.add(new Seahorse(aqua)); objects.add(new Penguin(aqua)); objects.add(new Coral(aqua)); objects.add(new Rock(aqua)); Why is this safe? |
|
Because a subclass inherits (or redefines) everything that the superclass
has or does. Anything you might do with a variable of the
superclass type can be done with an instance of the subclass type.
for ( AquariumObject obj : objects ) obj.move(); |
Dynamic Binding
The actual code that will be invoked depends on the actual type (the class) of the object in the variable at run-time. In other words, the method call is dynamically bound to a specific method body as the program is running. |