Java Reference
In-Depth Information
The effect is identical to the inner-class version above, with the difference that we do not need
to define separate named classes for the listeners and that the definition of the listener method is
closer to the registration of the listener with the menu item.
The scope coloring in BlueJ's editor gives us some hints that may help in understanding this
structure (Figure 11.4). The green shading indicates a class, the yellowish color shows a method
definition, and the white background identifies a method body. We can see that the body of the
makeMenuBar method contains, very tightly packed, two (strange-looking) class definitions,
which each have a single method definition with a short body.
Figure 11.4
Scope coloring with
two anonymous inner
When using an anonymous inner class, we create an inner class without naming it and immedi-
ately create a single instance of the class. In the action-listener code above, this is done with the
code fragment
new ActionListener() {
public void actionPerformed(ActionEvent e) { openFile(); }
An anonymous inner class is created by naming a supertype (often an abstract class or an
interface—here ActionListener ), followed by a block that contains an implementation for
its abstract methods. This looks unusual, because it is not otherwise permitted to create an
instance of an abstract class or interface directly.
In this example, we create a new subtype of ActionListener that implements the action-
Performed method. This new class does not receive a name. Instead, we precede it with the
new keyword to create a single instance of this class.
In our example, this single instance is an action-listener object (it is of a subtype of
ActionListener ). It can be passed to a menu item's addActionListener method and
Search WWH ::

Custom Search