Java Reference
In-Depth Information
Create the Animal superclass in your version of the project. Make the changes discussed
above. Ensure that the simulation works in a similar manner as before. You should be able to
check this by having the old and new versions of the project open side by side, for instance,
and making identical calls on Simulator objects in both, expecting identical outcomes.
Exercise 10.32 How has using inheritance improved the project so far? Discuss this.
10.3.2 Abstract methods
So far, use of the Animal superclass has helped to avoid a lot of the code duplication in the
Rabbit and Fox classes, and has potentially made it easier to add new animal types in the
future. However, as we have seen in Chapter 8, intelligent use of inheritance should also sim-
plify the client class—in this case, Simulator . We shall investigate this now.
In the Simulator class, we have used separate typed lists of foxes and rabbits and per-list
iteration code to implement each simulation step. The relevant code is shown in Code 10.4.
Now that we have the Animal class, we can improve this. Because all objects in our animal
collections are a subtype of Animal , we can merge them into a single collection and hence
iterate just once using the Animal type. However, one problem with this is evident from the
single-list solution in Code 10.5. Although we know that each item in the list is an Animal , we
still have to work out which type of animal it is in order to call the correct action method for its
type— run or hunt . We determine the type using the instanceof operator.
The fact that in Code 10.5 each type of animal must be tested for and cast separately and that
special code exists for each animal class is a good sign that we have not taken full advantage of
what inheritance has to offer. A better solution is to place a method in the superclass ( Animal ),
Code 10.5
An unsatisfactory
single-list solution to
making animals act
for (Iterator<Animal> it = animals.iterator(); it.hasNext(); ) {
Animal animal = it.next();
if (animal instanceof Rabbit) {
Rabbit rabbit = (Rabbit) animal;
r abbit.run(newAnimals);
}
else if (animal instanceof Fox) {
Fox fox = (Fox) animal;
fox.hunt(newAnimals);
}
else {
System.out.println( "found unknown animal" );
}
// Remove dead animals from the simulation.
if (! animal.isAlive()) {
it.remove();
}
}
 
Search WWH ::




Custom Search