Java Reference
In-Depth Information
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 . This will have its own rabbits. We 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 members 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 will be 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 will see that when each Rabbit object is displayed, it will also show
its parent hat.
Local Nested Classes
You can define a class inside a method - where it is called a local nested class . It is also referred to as a
local inner class , since a non-static nested class is often referred to as an inner class . You can only create
objects of a local inner class locally - that is, within the method in which the class definition appears.
This is useful when the computation in a method requires the use of a specialized class that is not
required or used elsewhere.
A local inner class can refer to variables declared in the method in which the definition appears, but
only if they are final .
Search WWH ::




Custom Search