Page 695 - Introduction to Programming with Java: A Problem Solving Approach
P. 695
The point of using an anonymous object is to avoid cluttering the code with a variable name when an object needs to be used only one time. The same idea can be applied to classes. The point of using an anonymous inner class is to avoid cluttering up the code with a class name when a class needs to be used only one time. For example, if a particular listener class listens to just one object, then the listener class needs to be used only one time as part of an addActionListener method call. Therefore, to unclutter your code, you may want to use an anonymous inner class for the listener.
Using an anonymous inner class is not a compiler requirement. It’s an elegance issue. In industry, you’ll find some people who say anonymous inner classes are elegant and you’ll find other people who say anony- mous inner classes are confusing. Do as you see fit. Better yet, do as your teacher sees fit.
Below, we show the syntax for an anonymous inner class. Naturally, there’s no class name. But there
is an interface name. So anonymous inner classes aren’t built from scratch; they’re built with the help of an 2
interface. Note the new operator. Formally speaking, the new operator isn’t part of the anonymous inner class. But practically speaking, since there’s no point in having an anonymous inner class without instantiat- ing it, you can think of the new operator as being part of the anonymous inner class syntax.
new <interface-name> () {
<class-body>
Here’s an example of an anonymous inner class, taken from the GreetingAnonymous program:
}
nameBox.addActionListener(
new ActionListener()
16.11 Anonymous Inner Classes 661
);
{
}
Apago P
public void actionPerformed(ActionEvent e)
{
...
} // end actionPerformed
// end inner-class constructor
DF Enhancer
For comparison purposes, here’s an example of a named (non-anonymous) inner class. It’s taken from the Greeting program:
private void createContents()
{
...
nameBox.addActionListener(new Listener());
// end createContents
private class Listener implements ActionListener
}
{
}
public void actionPerformed(ActionEvent e)
{
...
} // end actionPerformed
// end class Listener
i
2 As an alternative, it’s legal to define an anonymous class with a superclass instead of an interface. Details are beyond the scope of this textbook.
is
s
a
a
n
ni
i
n
nt
te
er
r
f
f
a
a
c
c
e
A
e
Ac
c
t
ti
i
o
on
n
L
L
i
is
st
te
e
n
ne
e
r
r