Java Reference
In-Depth Information
name = rabbitNames[index] + (++rabbitNamesCount[index]);
}
// String representation of a rabbit
public String toString() {
return name;
}
}
}
Directory "TryNestedClass"
Note that the constructor in the Rabbit class can access the select member of the enclosing class, Ma-
gicHat , without qualification. This is possible only 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.
You can use the following application class to try out the 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"));
}
}
Directory "TryNestedClass"
You should save this source file in the same directory as MagicHat.java . When I ran the program, I got
the following output:
Gray Topper contains:
Floppsy1 Moppsy1 Gnasher1 Floppsy2 Thumper1
Black Topper contains:
Moppsy2 Gnasher2 Floppsy3 Floppsy4
Baseball Cap contains:
Moppsy3
You are likely to get something different.
How It Works
Each MagicHat object contains 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+se-
Search WWH ::




Custom Search