Java Reference
In-Depth Information
Nested static classes that are
public
can be accessed from everywhere by specifying
the name of the outer class followed by a dot and then the name of the nested classes.
Within the outer class, nested static classes can be accessed directly by specifying only
thenameoftheclass.
Note that nested classes can be defined without an access privilege modifier. Then
they will be accessible only within the package. Alternatively, they can be defined using
the
private
keyword. Such classes will only be visible within the outer class. Although
uncommon, nested classes can also be defined as
protected
. Then they will be accessible
within the package and within the subclasses of the outer class.
The new code for the typing game seems a little more compact. We did not have to
create a new outer class. Probably, we do not want anyone outside the
TypingGame
class to
be aware of our nested class and we can define it as
private
.
The classes
Double
and
Float
inside the class
Rectangle2D
are examples of nested
static classes.
10.2.2 Inner Classes
Nested classes in Java that are not static are called
inner
. In order to show an example
of an inner class, let us refactor our program and create a separate class that handles
populating the
ArrayList
with random characters.
public class
TypingGame
{
public static void
main(String [] args)
throws
Exception
{
new
PopulateChars () ;
JFrame frame =
new
JFrame () ;
frame. setVisible(
true
);
}
}
public class
PopulateChars
{
ArrayList
<
Character
>
charList ;
public
PopulateChars ()
{
charList =
new
ArrayList
<
Character
>
() ;
Timer timer =
new
Timer(200,
new
TimerListener ()) ;
timer. start() ;
}
private class
TimerListener
implements
ActionListener
{
public void
actionPerformed(ActionEvent e)
{
charList .add((
char
)(
'a'
+(
int
) ((Math . random()
26)))) ;
∗
System. out . println ( charList ) ;
}
}
}
Now the
TimerListener
class is an inner class for the
PopulateChars
class. A nice
feature of inner classes is that they have access to the variables of the outer class. For ex-
ample, the
actionPerformed
method has access to the variable
charList
in the outer class.
However, note that there can be multiple instances of the
PopulateChars
class. Therefore,
every object of the
TimerListener
class must be associated with exactly one object that
belongs to the
PopulateChars
class. If this is not the case, then the reference to the vari-
able
charList
can be ambiguous. Figure 10.1 shows how the object that belongs to the
TimerListener
class must be related to an object of the outer class.