Java Reference
In-Depth Information
If the preceding discussion seems a bit confusing in the abstract, you can get a better idea of how a nested
class works in practice with a simple example. You create a class MagicHat that defines an object containing
a variable number of Rabbit objects. You put the definition for the class Rabbit inside the definition of the
class MagicHat , so Rabbit is an example of a nested class. The basic structure of MagicHat.java is:
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 you want to be able to have static members of this
class. You will see a little later in the chapter how it might work with a non-static nested class.
TRY IT OUT: Rabbits out of Hats
Let's add the details 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(Rabbit rabbit : rabbits) {
Search WWH ::




Custom Search