Java Reference
In-Depth Information
}
}
}
Directory "TryNestedClass2"
I put this version in the new folder TryNestedClass2 . The only changes are the deletion of the static
keyword in the definition of the Rabbit class and the movement of data members relating to rabbit names
to the MagicHat class. You can run this with the same version of TryNestedClass , and it should produce
output much the same as before.
How It Works
Although the output is much the same, what is happening is distinctly different. The Rabbit objects that
are created in the MagicHat constructor are now associated with the current MagicHat object that is be-
ing constructed. The Rabbit() constructor call is actually this.Rabbit() .
Using a Nested Class Outside the Top-Level Class
You can create objects of an inner class outside the top-level class containing the inner class. As I discussed,
how you do this depends on whether the nested class is a static member of the enclosing class. With the first
version of the MagicHat class, with a static Rabbit class, you could create an independent rabbit by adding
the following statement to the end of main() :
System.out.println("An independent rabbit: " + new MagicHat.Rabbit());
This Rabbit object is completely free — there is no MagicHat object to contain and restrain it. In the
case of a non-static Rabbit class, things are different. Let's try this using a modified version of the previous
program.
TRY IT OUT: Free-Range Rabbits (Almost)
You can see how this works by modifying the main() method in TryNestedClass to create another Ma-
gicHat object, and then create a Rabbit object for it:
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"));
MagicHat oldHat = new MagicHat("Old hat");
// New hat
object
MagicHat.Rabbit rabbit = oldHat.new Rabbit();
// Create
Search WWH ::




Custom Search