Java Reference
In-Depth Information
We will use anonymous local classes only when we want to create an object from
a class and we will never need to refer to the class again.
Note the unusual syntax for creating anonymous local classes. We write new
ActionListener() . However, this does not mean that we are creating a new object of
type ActionListener . After all, ActionListener is an interface and it is illegal to instan-
tiate an object from an interface. We are actually creating a new object that belongs to a
class with name X , where we are not naming the X class. What we require is that the X class
inherits from the ActionListener class. In other words, the above code is equivalent to the
following code.
public class TypingGame
{
public static void main(String [] args)
{
final ArrayList
<
Character
>
charList = new ArrayList
<>
() ;
class X implements ActionListener {
public void actionPerformed(ActionEvent e) {
charList .add(( char )( 'a' +( int ) ((Math . random()
26)))) ;
System. out . println ( charList ) ;
}
} Timer t = new Timer(1000, new X() ) ;
t. start() ;
JFrame frame = new JFrame () ;
frame. setVisible( true );
}
}
The only difference between the above and the original rewrite is that the X class is
given a name. However, since the X class will be referenced only once, the first version of
the code is preferred. It is shorter and more intuitive. Consider again the anonymous local
class creation.
Timer t = new Timer(200, new ActionListener () {
public void actionPerformed(ActionEvent e)
{
charList .add(( char )(
'a'
+( int ) ((Math . random()
26)))) ;
System. out . println ( charList ) ;
}
}
);
The code creates a timer that will be executed every 200 milliseconds. Every 200 mil-
liseconds, the actionPerformed method will be executed. The rest of the code is simply
syntax that circumvents the fact that Java allows only an object, and not a method, to be
a method parameter.
The observant reader may have noticed that the variable charList was changed to
final . This is not a coincidence.
A local class can access only the constant (i.e., final ) variables of the method
in which it is defined. The reason is that an object that belongs to a local class can
continue to exist after the method terminates. Local variables that are defined as final
are preserved so that they can be accessed long after the method has terminated. The
reason they are preserved is because they are defined as final and will therefore not
change.
 
Search WWH ::




Custom Search