Java Reference
In-Depth Information
where the compiler bytecode will keep track of the Dimension object that
provides the width and height.
We can in fact cascade several such calls, using the object returned in the left
method to call the next method on the right:
a = getA ().methodB ().aMethodC ().variableX;
This anonymity eliminates from the code a lot of unnecessary variables and makes
it more readable.
With the inner classes we can take this concept to another level by creating
and instantiating a class without bothering to give the class a name. In the code
below an instance of the ActionListener class is created in the parameter of
the addActionListener method:
public class AnOuterClass extends JApplet
{
int fVar = 0;
JButton fBut = new JButton ("OK");
public AnOuterClass () {
fBut.addActionListener
(// Left parenthesis of method
new ActionListener () { // no name given for this
// ActionListener object
// Override actionPerformed as usual
public void actionPerformed (ActionEvent e) {
fVar++;
System.out.println ( " Pressed " + fVar + " times " );
}
}
); // Right parenthesis of method
add (fBut);
} // ctor
} // class AnOuterClass
Here in one step we created a class that implemented the ActionListener
interface and created an instance of it for use by the button. The compiler will
create a class file name AnOuterClass$1.class where a number, in this case
1 ,isused to identify the class file name for an anonymous inner class.
7.5.3 Adapter classes
The Java class library also includes adapter classes ,which make writing lis-
tener classes more convenient. While the listener architecture greatly improves
the efficiency and capabilities of event handling, there are some complications
 
Search WWH ::




Custom Search