Java Reference
In-Depth Information
Instead of the old Math.random() method that we have been using up to now to generate pseudo-
random values, we are using an object of the class Random that is defined in the package java.util .
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 we 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 will generate a random index value that will always be legal for the array size.
We can now add the definition of the Rabbit class. When we create a Rabbit object, we want it to
have a unique name so we can distinguish one Rabbit from another. We can generate unique names
by selecting one from a limited set of fixed names, and then appending an integer that is different each
time the base name is used. Here's what we 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
name = rabbitNames[index] + (++rabbitNamesCount[index]);
}
// String representation of a rabbit
public String toString() {
return name;
}
}
}
Note that the constructor in the Rabbit class can access the select member of the enclosing class
MagicHat , without qualification. This is only possible with static members of the enclosing class - you
can't refer to non-static members of the enclosing class here because there is no object of type
MagicHat associated with it.
We can use the following application class to try out our nested class:
public class TryNestedClass {
static public void main(String[] args) {
// Create three magic hats and output them
System.out.println(new MagicHat("Gray Topper"));
System.out.println(new MagicHat("Black Topper"));
System.out.println(new MagicHat("Baseball Cap"));
}
}
Search WWH ::




Custom Search