Java Reference
In-Depth Information
Note that sometimes a method with the same name and parameters can exist in the
inner class and the outer class. Here is an example of how such a method can be called.
public class
PopulateChars
{
ArrayList
<
Character
>
charList ;
public
PopulateChars ()
{
charList =
new
ArrayList
<
Character
>
() ;
}
public void
printChars ()
{
System. out . println ( charList ) ;
}
public class
TimerListener
implements
ActionListener
{
{
public void
actionPerformed(ActionEvent e)
charList .add((
char
)(
'a'
+(
int
) ((Math . random()
∗
26)))) ;
PopulateChars .
this
.printChars();
}
public void
printChars ()
{
}
}
}
The syntax is
PopulateChars.this.printChars()
. This means go to the outer ob-
ject that belongs to the
PopulateChars
class, get its
this
reference (i.e., the reference
to the outer object), and call the
printChars
method on it. Conversely, the syntax
PopulateChars.printChars()
can be used to call a static method of the outer class when
a method with the same name exists in the nested class.
10.2.3 Local Classes
Declaring a class inside a class is useful when we want to quickly define a class without
creating a new outer class. As we saw, nested classes are particularly useful for event han-
dling. Sometimes, however, one needs to create an object that belongs to a class inside a
method. Such a class is called a
local class
and can have a name, but it is usually anony-
mous. For example, when we need to create a callback method, we can just create an object
that supports this method. The object can belong to a new class that is created on the fly.
Note, however, that if the class is not given a name, then it cannot be reused to create more
objects of the class. Here is how our typing program can be rewritten to use anonymous
local classes.
public class
TypingGame
{
public static void
main(String [] args)
{
final
ArrayList
<
Character
>
charList =
new
ArrayList
<
Character
>
() ;
Timer t =
new
Timer(200,
new
ActionListener ()
{
public void
actionPerformed(ActionEvent e)
{
charList .add((
char
)(
'a'
+(
int
) ((Math . random()
26)))) ;
∗
System. out . println ( charList ) ;
}
}
);
t. start() ;
JFrame frame =
new
JFrame () ;
frame. setVisible(
true
);
}
}