Java Reference
In-Depth Information
the object-oriented approach in which classes are strictly modular and separate.
However, if these classes are kept small and only used where best needed, they
can make Java code easier both to write and to read.
7.5.1 Inner classes
A technique that came with Java 1.1 allowed the nesting of classes. That is,
inner classes can be inserted inside other classes. For example, in the following
code we show how to put the definition of the class AnInnerClass inside the
constructor:
public class AnOuterClass
{
int fVar;
public AnOuterClass () {
... other code ...
class AnInnerClass {
int b;
AnInnerClass () {
b = 4. * fVar;
}
} // class AnInnerClass
AnInnerClass inner = new AnInnerClass ();
...other code...
}
void someMethod () {
...code . . .
}
} // class AnOuterClass
The scope ,which refers to the variables and methods accessible to a given
section of code, for the inner classes includes the instance variables and methods
of the parent class.
The most common use of inner classes is with event handling. The event model
allows us to make any class into a listener for our events. However, this can lead
to listener classes spread throughout the code, which makes the programs less
readable. With inner classes we can put the listener class definition immediately
adjacent to the code for the component that uses the listener. For example, in the
following code segment, an ActionListener class is placed next to where an
instance of it is added to a button:
 
Search WWH ::




Custom Search