Java Reference
In-Depth Information
redefinitions in the subclasses. Both Fox and Rabbit will define their own versions of get-
BreedingAge to return their particular values of BREEDING_AGE :
Concept:
Superclass
method calls.
Calls to non-private
instance methods
from within a su-
perclass are always
evaluated in the
wider context of the
object's dynamic
type.
/**
* @return The age at which a rabbit starts to breed.
*/
public int getBreedingAge()
{
return BREEDING_AGE;
}
So even though the call to getBreedingAge originates in the code of the superclass, the
method called is defined in the subclass. This may seem mysterious at first but it is based on the
same principles we described in Chapter 9 in using the dynamic type of an object to determine
which version of a method is called at runtime. The technique illustrated here makes it possible
for each instance to use the value appropriate to its subclass type. Using the same approach, we
can move the remaining methods, incrementAge and breed , to the superclass.
Exercise 10.43 Using your latest version of the project (or the foxes-and-rabbits-v2 project
in case you have not done all the exercises), record the number of foxes and rabbits over a
small number of steps, to prepare for regression testing of the changes to follow.
Exercise 10.44 Move the age field from Fox and Rabbit to Animal . Initialize it to zero
in the constructor. Provide accessor and mutator methods for it and use these in Fox and
Rabbit rather than in direct accesses to the field. Make sure the program compiles and
runs as before.
Exercise 10.45 Move the canBreed method from Fox and Rabbit to Animal, and
rewrite it as shown in Code 10.8. Provide appropriate versions of getBreedingAge in Fox
and Rabbit that return the distinctive breeding age values.
Exercise 10.46 Move the incrementAge method from Fox and Rabbit to Animal
by providing an abstract getMaxAge method in Animal and concrete versions in Fox and
Rabbit .
Exercise 10.47 Can the breed method be moved to Animal ? If so, make this change.
Exercise 10.48 In light of all the changes you have made to these three classes, reconsider
the visibility of each method and make any changes you feel are appropriate.
Exercise 10.49 Was it possible to make these changes without having any impact on any
other classes in the project? If so, what does this suggest about the degrees of encapsulation
and coupling that were present in the original version?
Exercise 10.50 Challenge exercise Define a completely new type of animal for the simula-
tion, as a subclass of Animal . You will need to decide what sort of impact its existence will
 
Search WWH ::




Custom Search