Java Reference
In-Depth Information
When I ran the program, I got the output:
Gray Topper contains:
Moppsy1 Moppsy2 Floppsy1
Black Topper contains:
Thumper1
Moppsy3
Thumper2 Gnasher1
Baseball Cap contains:
Moppsy4 Moppsy5 Thumper3
You are likely to get something different.
How It Works
Each
MagicHat
object will contain a random number of
Rabbit
objects. The constructor for a
MagicHat
object stores the name of the hat in its private member
hatName
, and generates a
Rabbit
array with at least one, and up to
maxRabbits
elements. This is done with the expression
1+select.nextInt(maxRabbits)
. Calling
nextInt()
with the argument
maxRabbits
will
return a value that is from
0
to
maxRabbits-1
inclusive. Adding
1
to this will result in a value from 1
to
maxRabbits
inclusive. The array so created is then filled with
Rabbit
objects.
The
MagicHat
class also has a method
toString()
method which returns a
String
object
containing the name of the hat and the names of all the rabbits in the hat. This assumes that the
Rabbit
class also has a
toString()
method defined. We will be able to use the
toString()
implicitly in an
output statement when we come to create and display
MagicHat
class objects.
The base names that we use to generate rabbit names are defined in the
static
array
rabbitNames[]
in the
Rabbit
class. The count for each base name, which we will append to the
base name to produce a unique name for a rabbit, is stored in the
static
array
rabbitNamesCount[]
. This has the same number of elements as the
rabbitNames
array, and each
element stores a value to be appended to the corresponding name in the
rabbitNames
array. The
Rabbit
class has the data member,
name
, to store a name that is initialized in the constructor. A
random base name is selected from the
rabbitNames[]
array using an index value from 0 up to one
less than the length of this array. We then append the current count for the name incremented by 1, so
successive uses of any base name such as
Gnasher
, for example, will produce names
Gnasher1
,
Gnasher2
, and so on. The
toString()
method for the class returns the name for the
Rabbit
object.
The method
main()
in
TryNestedClass
creates three
MagicHat
objects and outputs the string
representation of each of them. Putting the object as an argument to the
println()
method will call
the
toString()
method for the object automatically, and the
String
object that is returned will be
output to the screen.
Using a Non-Static Nested Class
In our previous example, we could define the
Rabbit
class as non-static by deleting the keyword
static
. However, if you try that, the program will no longer compile and run. The problem is the
static data members'
rabbitNames
and
rabbitNamesCount
in the
Rabbit
class. We saw earlier
that a non-static nested class cannot have static members, so we must seek an alternative way of dealing
with names.