Java Reference
In-Depth Information
Because accessEnclosingClass() is nonstatic, EnclosedClass must be
instantiated beforethismethodcanbecalled.Thisinstantiation musttakeplaceviaan
instance of EnclosingClass . Listing 3-6 accomplishes these tasks.
Listing 3-6. Calling a nonstatic member class's instance method
class NSMCDemo
public static void main(String[] args)
EnclosingClass ec = new EnclosingClass();
Output: 1
Listing3-6 ' s main() methodfirstinstantiates EnclosingClass andsavesitsref-
erence in local variable ec . Then, main() uses this reference as a prefix to the new
operator, to instantiate EnclosedClass , whose reference is then used to call ac-
cessEnclosingClass() , which outputs 1 .
Note Prefixing new withareferencetotheenclosingclassisrare.Instead,youwill
typically call an enclosed class's constructor from within a constructor or an instance
method of its enclosing class.
Suppose you need to maintain a to-do list of items, where each item consists of a
nameandadescription.Aftersomethought,youcreate Listing3-7 's ToDo classtoim-
plement these items.
Listing 3-7. Implementing to-do items as name-description pairs
class ToDo
private String name;
private String desc;
ToDo(String name, String desc)
{ = name;
this.desc = desc;
Search WWH ::

Custom Search