Inner Classes in Depth
By Bruce Eckel
In Java 1.1, it's possible to place a class definition within another class definition, creating an "inner class" that allows you to group classes that logically belong together and to control the visibility of one within the other. However, it's important to understand that inner classes are distinctly different from composition.
You create an inner class by placing the class definition inside a surrounding class, as in
Listing One. This example hides the class definitions for Contents and Destination inside Parcel1 but note that it doesn't make them handles or objects; those must be created explicitly. This is done in main(), and it reveals a somewhat odd syntax. Creating an object of the outer class follows the typical form: Parcel1 p=new Parcel1();
An object of the inner class would be of type OuterClassName.InnerClassName, but to create the object you don't refer to the outer class name Parcel1; instead, you must use an object of the outer class to make an object of the inner class, like so: Parcel1.Contents c=p.new Contents().
Without an object of the outer class, you can't create an object of the inner class because every inner-class object is quietly connected to the outer-class object from which it was created.
Usually, an outer-class method will return a handle to an inner class, as in