Java Reference
In-Depth Information
rabbit object
System.out.println(oldHat);
// Show the hat
System.out.println("\nNew rabbit is: " + rabbit);
// Display the
rabbit
}
Directory "TryNestedClass3"
I put this in the TryNestedClass3 folder. The output that I got was as follows:
Gray Topper contains:
Thumper1
Black Topper contains:
Moppsy1 Thumper2 Thumper3
Baseball Cap contains:
Floppsy1 Floppsy2 Thumper4
Old hat contains:
Floppsy3 Thumper5 Thumper6 Thumper7 Thumper8
New rabbit is: Thumper9
How It Works
The new code first creates a MagicHat object, oldHat , which has its own rabbits. You then use this object
to create an object of the class MagicHat.Rabbit . This is how a nested class type is referenced — with
the top-level class name as a qualifier. You can only call the constructor for the nested class in this case
by qualifying it with a MagicHat object name. This is because a non-static nested class can refer to mem-
bers of the top-level class — including instance members. Therefore, an instance of the top-level class
must exist for this to be possible.
Note how the top-level object is used in the constructor call. The object name qualifier goes before the
keyword new , which precedes the constructor call for the inner class. This creates an object, rabbit , in
the context of the object oldHat . This doesn't mean oldHat has rabbit as a member. It means that if
top-level members are used in the inner class, they are the members for oldHat . You can see from the
example that the name of the new rabbit is not part of the oldHat object, although it is associated with
oldHat . You could demonstrate this by modifying the toString() method in the Rabbit class to:
public String toString() {
return name + " parent: "+hatName;
}
If you run the program again, you see that when each Rabbit object is displayed, it also shows its parent
hat.
Local Nested Classes
Search WWH ::




Custom Search