Java Reference
In-Depth Information
Method cal lback
is when a method is passed as a parameter. When an event occurs,
the method will be called back. Java does not directly support method callbacks.
The reason is that methods themselves cannot be passed as arguments to methods.
Alternatively, one needs to create a class that supports the required methods and
pass an object of that class as a parameter. Java uses interfaces to guarantee that the
object supports the required methods.
10.2 Nested Classes
It seems burdensome to create a brand new class every time we want to implement a
method callback. To simplify the process, Java allows us to create a class within another
class. Such classes are referred to as
nested classes
.
10.2.1 Static Nested Classes
Let us now explore how nested classes apply to our typing program. First, consider the
following rewrite of our typing game.
public class
TypingGame
{
public static void
main(String [] args)
{
Timer t =
new
Timer(1000,
new
TimerListener ()) ;
t. start() ;
JFrame frame =
new
JFrame () ;
frame. setVisible(
true
);
}
public static class
TimerListener
implements
ActionListener
{
ArrayList
<
Character
>
charList =
new
ArrayList
<>
() ;
public void
actionPerformed(ActionEvent e)
{
charList .add((
char
)(
'a'
+(
int
) ((Math . random()
26)))) ;
∗
System. out . println ( charList ) ;
}
}
}
Now the
TimerListener
class is defined inside the
TypingGame
class. The class is defined
as
static
because it is not connected to a particular instance of the outer
TypingGame
class.
In other words, objects that belong to the
TimerListener
class will not be associated with
an object of the
TypingGame
class. Note that defining the
TimerListener
class without
using the
static
keyword will result in an error. The reason is that this will imply that
the class is associated with an instance of the
TypingGame
class. However, the
TypingGame
class is never instantiated.
The nested class is defined as
public
, which means that everyone can create an instance
of it. For example, the following code is valid outside the
TypingGame
class.
TypingGame . TimerListener
l i s t e n e r =
new
TypingGame . TimerListener ( ) ;