A new technique that came with Java 1.1 was the nesting
of classes. That is, a so-called inner class can be defined
and instantiated all inside another classes.
Inner classes fall into four rough categories: static
and instance member classes, local classes, and annoymous
classes.
Member classes are included in the class definition
just like fields and methods. A member class can be static with
access only to the static members of the class to which it belongs,
or it can be an instance class with access to both the static and
instance members of the class that contains it.
An local class is defined within a code block,
typically in a method. Like the value of local variable, an instance
of a local class exists only during the processing of the method
unless a reference to it is maintained. For example, in the following
code we show how to put the definition of AnInnerClass
inside a constructor:
public
class AnOuterClass
{
int
fA;
public AnOuterClass
()
{
... other code ...
class
AnInnerClass
{
int
b;
AnInnerClass
() {
b
= 4. * fA;
}
} //
class AnInnerClass
AnInnerClass inner = new
AnInnerClass ();
...
}
// ctor
void outerMethod
() {
...
} //
outerMethod
} //
class AnOuterClass
|
The scope of the inner classes includes the
instance variables and methods of the parent class.
A common use of inner classes is in event handling.
The new event model allows us to make any class into a listener
for our events. However, this can lead to listener classes spread
out through the code and making the programs less readable.
With inner classes, we can put the listener class
definition adjacent to the code for the component that uses the
listener. For example, in the following code segement, an ActionListener
class is placed next to where an instance of it is added to a
button::
public class AnOuterClass extends
java.applet.Applet
{
Button fBt = new
Button ("OK");
public AnOuterClass
()
{
int
i=0;
class
AnInnerClass implements ActionListener
{
public
void actionPerformed (ActionEvent e) {
i++;
System.out.println
("Pressed "+i+" times");
}
}
bt.addActionListener
(new
AnInnerClass
());
add (bt);
} //
class AnInnerClass
} // class AnOuterClass
|
The compiler will separate out these inner classes
and create separate class
files for them. The names will be prepended with the outer class
name. After you compile the above code, you would find the following
file in the directory:
AnOuterClass$AnInnerClass.class
Latest update: Nov. 3, 2004
|