Java Reference
In-Depth Information
public class MagicHat {
// Definition of the MagicHat class...
// Nested class to define a rabbit
static class Rabbit {
// Definition of the Rabbit class...
}
}
Here the nested class is defined as static because we want to be able to have static members of this
class. We will see a little later how it might work with a non-static nested class.
Try It Out - Rabbits Out of Hats
Let's add the detail of the MagicHat class definition:
import java.util.Random; // Import Random class
public class MagicHat {
static int maxRabbits = 5; // Maximum rabbits in a hat
static Random select = new Random(); // Random number generator
// Constructor for a hat
public MagicHat(String hatName) {
this.hatName = hatName; // Store the hat name
rabbits = new Rabbit[1+select.nextInt(maxRabbits)]; // Random rabbits
for(int i = 0; i < rabbits.length; i++)
rabbits[i] = new Rabbit(); // Create the rabbits
}
// String representation of a hat
public String toString() {
// Hat name first...
String hatString = "\n" + hatName + " contains:\n";
for(int i = 0; i < rabbits.length; i++)
hatString += "\t" + rabbits[i] + " "; // 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...
}
}
Search WWH ::




Custom Search