Java Reference
In-Depth Information
Exercise 10.24 Each animal is always held in two different data structures: the Field and
the Simulator 's rabbits and foxes lists. There is a risk that they could be inconsistent
with each other. Check that you thoroughly understand how the Field and the animal lists are
kept consistent between the simulateOneStep method in Simulator , hunt in Fox , and
run in Rabbit .
Exercise 10.25 Do you think it would be better for Simulator not to keep separate lists
of foxes and rabbits but to generate these lists again from the contents of the field at the be-
ginning of each simulation step? Discuss this.
Exercise 10.26 Write a test to ensure that, at the end of a simulation step, there is no ani-
mal (dead or alive) in the field that is not in one of the lists and vice versa. Should there be any
dead animals in any of those places at that stage?
Taking steps to improve the simulation
Now that we have examined how the simulation operates, we are in a position to make
improvements to its internal design and implementation. Making progressive improvements
through the introduction of new programming features will be the focus of subsequent sections.
There are several points at which we could start, but one of the most obvious weaknesses is that
no attempt has been made to exploit the advantages of inheritance in the implementation of the
Fox and Rabbit classes, which share a lot of common elements. In order to do this, we shall
introduce the concept of an abstract class.
Exercise 10.27 Identify the similarities and differences between the Fox and Rabbit
classes. Make separate lists of the fields, methods, and constructors, and distinguish between
the class variables (static fields) and instance variables.
Exercise 10.28 Candidate methods for placement in a superclass are those that are identi-
cal in all subclasses. Which methods are truly identical in the Fox and Rabbit classes? In
reaching a conclusion, you might like to consider the effect of substituting the values of class
variables into the bodies of the methods that use them.
Exercise 10.29 In the current version of the simulation, the values of all similarly named
class variables are different. If the two values of a particular class variable ( BREEDING_AGE ,
say) were identical, would it make any difference to your assessment of which methods are
truly identical?
Abstract classes
Chapter 8 introduced concepts such as inheritance and polymorphism that we ought to be able
to exploit in the simulation application. For instance, the Fox and Rabbit classes share many
similar characteristics that suggest they should be subclasses of a common superclass, such as
Animal . In this section, we will start to make such changes in order to improve the design and
Search WWH ::

Custom Search