Java Reference
In-Depth Information
hatString += "
" + rabbit;
// Add the rabbits
strings
}
return hatString;
}
private String hatName;
// Name of the hat
private Rabbit rabbits[];
// Rabbits in the
hat
// Nested class to define a rabbit
static class Rabbit {
// Definition of the Rabbit class...
}
}
Directory "TryNestedClass"
You can save the source file in a new directory, TryNestedClass . Instead of the old Math.random()
method that you have been using up to now to generate pseudo-random values, you are using an object
of the class Random that is defined in the java.util package. An object of type Random has a variety
of methods to generate pseudo-random values of different types, and with different ranges. The method
nextInt() that you are using here returns an integer that is zero or greater, but less than the integer value
you pass as an argument. Thus, if you pass the length of an array to it, it generates a random index value
that is always legal for the array size.
You can now add the definition of the Rabbit class. When you create a Rabbit object, you want it to
have a unique name so you can distinguish one Rabbit from another. You can generate unique names by
selecting one of a limited set of fixed names and then appending an integer that is different each time the
base name is used. Here's what you need to add for the Rabbit class definition:
public class MagicHat {
// Definition of the MagicHat class - as before...
// Nested class to define a rabbit
static class Rabbit {
// A name is a rabbit name from rabbitNames followed by an integer
static private String[] rabbitNames = {"Floppsy", "Moppsy",
"Gnasher", "Thumper"};
static private int[] rabbitNamesCount = new
int[rabbitNames.length];
private String name;
// Name of the rabbit
// Constructor for a rabbit
public Rabbit() {
int index = select.nextInt(rabbitNames.length); // Get random
name index
Search WWH ::




Custom Search