Polymorphism & Dynamic Binding

Classes and Interfaces

Aquarium Example, continued

We can declare variables to be of an abstract type, even though when we construct them we must specify a concrete type:
    AquariumObject obj = new AquaFish(aqua));
We can even use the same abstract type variable to refer to objects of different concrete classes:
    obj = new Crab(aqua);
    obj = new Seahorse(aqua);

Or we could construct them and put them in an ArrayList of the abstract 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));
        poly: many
        morph: shape
A variable that is declared to be of an abstract type can take on the type of any class that implements the interface (take on many shapes).
We could then tell them all to move, for example.
    for ( AquariumObject item : objects )
Dynamic Binding
The actual code that will be invoked depends on the concrete type (the class) of the object in the variable. In other words, the method call is dynamically bound to a specific method body as the program is running.

Alyce Brady, Kalamazoo College