Java Reference
In-Depth Information
Forbrevity,Ihaveomittedfromthe
Animal
hierarchy
abstract Robin
,
Canary
,
Trout
, and
Salmon
classes that generalize robins, canaries,
trout, and salmon. Perhaps you might want to include these classes in the
hierarchy.
Althoughthisexerciseillustratestheaccuratemodelingofanaturalscenario
usinginheritance,italsorevealsthepotentialfor
class explosion
—toomany
classes may be introduced to model a scenario, and it might be difficult to
maintain all these classes. Keep this in mind when modeling with inherit-
ance.
3. Continuing from the previous exercise, declare an
Animals
class with a
main()
method.Thismethodfirstdeclaresan
animals
arraythatisini-
tializedto
AmericanRobin
,
RainbowTrout
,
DomesticCanary
,and
SockeyeSalmon
objects. The method then iterates over this array, first
outputting
animals[i]
(which causes
toString()
to be called), and
then calling each object's
eat()
and
move()
methods (demonstrating
subtype polymorphism).
4. Continuingfromthepreviousexercise,declarea
public Countable
in-
terfacewitha
String getID()
method.Modify
Animal
toimplement
Countable
andhavethismethodreturn
kind
'svalue.Modify
Animals
to initialize the
animals
array to
AmericanRobin
,
RainbowTrout
,
DomesticCanary
,
SockeyeSalmon
,
RainbowTrout
, and
Amer-
icanRobin
objects.Also,introducecodethatcomputesacensusofeach
ing 2-50
.
Listing 2-50.
The
Census
class stores census data on four kinds of animals
public class Census
{
public final static int SIZE = 4;
private String[] IDs;
private int[] counts;
public Census()
{
IDs = new String[SIZE];
counts = new int[SIZE];
}
public String get(int index)
{