Java Reference
In-Depth Information
Creating Objects of Inner Classes
Creating objects of a local inner class, an anonymous class, and a static member class is straightforward. Objects
of a local inner class are created using the new operator inside the block, which declares the class. An object of an
anonymous class is created at the same time the class is declared. A static member class is another type of top-level
class. You create objects of a static member class the same way you create objects of a top-level class.
Note that to have an object of a member inner class, a local inner class, and an anonymous class, you must have
an object of the enclosing class. In the previous examples of local inner classes and anonymous inner classes, you had
placed these classes inside instance methods. You had an instance of the enclosing class on which you called those
instance methods. Therefore, instances of those local inner classes and anonymous inner classes had the instance of
their enclosing classes on which those methods were called. For example, in Listing 2-4, first you created an instance
of TitleList class and you stored its reference in t1 as shown:
TitleList tl = new TitleList();
To get the iterator of t1 , you called the titleIterator() method:
Iterator iterator = tl.titleIterator();
The method call t1.titleIterator() creates an instance of the TitleIterator local inner class inside the
titleIterator() method as
TitleIterator titleIterator = new TitleIterator();
Here, titleIterator is an instance of the local inner class and it exists within t1 , which is an instance of its
enclosing class. This relationship exists for all inner classes as depicted in Figure 2-1 .
An instance of the
enclosing class - TitleList
An instance of the local
inner class - TitleIterator
t1
titleIt erator
Figure 2-1. The relationship between an instance of an inner class and an instance of its enclosing class
there are situations where an instance of the enclosing class is not required for the existence of an instance
of a local inner class or an anonymous inner class. this happens when local inner classes or anonymous inner classes
are defined inside a static-context, for example, inside a static method or a static initializer. I will discuss these cases
later in this chapter.
Note
 
 
Search WWH ::




Custom Search