Java Reference
In-Depth Information
Discussion
Anonymous inner classes are declared and instantiated at the same time, using the new oper-
ator with the name of an existing class or interface. If you name a class, it will be subclassed;
if you name an interface, the anonymous class will extend
java.lang.Object
and imple-
ment the named interface. The paradigm is:
b.addActionListener(new ActionListener( ) {
public void actionPerformed(ActionEvent e) {
showStatus("Thanks for pushing my second button!");
}
});
Did you notice the
});
by itself on the last line? Good, because it's important. The
}
termin-
ates the definition of the inner class, while the
)
ends the argument list to the
addAc-
tionListener
method; the single argument inside the parenthesis is an argument of type
ActionListener
that refers to the one and only instance created of your anonymous class.
Example 14-4
contains a complete example.
Example 14-4. ButtonDemo2c.java
public
public class
class
ButtonDemo2c
ButtonDemo2c
extends
extends
Applet
{
Button
b
;
public
public
void
void
init
() {
add
(
b
=
new
new
Button
(
"A button"
));
b
.
addActionListener
(
new
new
ActionListener
() {
public
public
void
void
actionPerformed
(
ActionEvent e
) {
showStatus
(
"Thanks for pushing my first button!"
);
}
});
add
(
b
=
new
new
Button
(
"Another button"
));
b
.
addActionListener
(
new
new
ActionListener
() {
public
public
void
void
actionPerformed
(
ActionEvent e
) {
showStatus
(
"Thanks for pushing my second button!"
);
}
});
}
}
The real benefit of these anonymous inner classes, by the way, is that they keep the action
handling code in the same place that the GUI control is being instantiated. This saves a lot of
looking back and forth to see what a GUI control really does.