Java Reference
In-Depth Information
return name;
}
}
}
The only changes are the deletion of the static keyword in the definition of the
Rabbit
class - the data
members relating to rabbit names have been moved 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 being 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 we
discussed, how you do this depends on whether the nested class is a static member of the enclosing
class. With the first version of our
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 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)
We can see how this works by modifying the method
main()
in
TryNestedClass
to create another
MagicHat
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 rabbit object
System.out.println(oldHat); // Show the hat
System.out.println("\nNew rabbit is: " + rabbit); // Display the rabbit
}
The output produced is:
Gray Topper contains:
Thumper1
Black Topper contains:
Moppsy1 Thumper2 Thumper3