Java Reference
In-Depth Information
pointer to outer
object
charList = [2,3,5]
PopulateChars object
TimerListener object
FIGURE 10.1:
Example of inner class.
In our example, a
TimerListener
object is created within the constructor of the
PopulateChars
class. The outer object for the new object of type
TimerListener
is the
object that created the
TimerListener
object. An inner object can also be created from
outside the outer class. However, the syntax is more involved because the outer object needs
to be explicitly identified. Here is an example.
public class
TypingGame
{
public static void
main(String [] args)
throws
Exception
{
PopulateChars populateChars =
new
PopulateChars () ;
Timer timer =
new
Timer(200 ,populateChars .
new
TimerListener ()) ;
timer. start() ;
JFrame frame =
new
JFrame () ;
frame. setVisible(
true
);
}
}
{
public class
PopulateChars
<
>
ArrayList
charList ;
public
PopulateChars ()
Character
{
charList =
new
ArrayList
<
Character
>
() ;
}
public class
TimerListener
implements
ActionListener
{
public void
actionPerformed(ActionEvent e)
{
charList .add((
char
)(
'a'
+(
int
) ((Math . random()
26)))) ;
∗
System. out . println ( charList ) ;
}
}
}
Examine the code
populateChars.new TimerListener()
. This means create a new
object of type
TimerListener
. However, instead of specifying the outer
PopulateChars
class, we need to specify the outer object:
populateChars
. The reason is that every inner
object needs to have a reference to an outer object. This is similar to class inheritance
because every object that belongs to a subclass needs to have a reference to an object that
belongs to the superclass.
Objects of nested static classes have a reference to the outer class. Conversely,
objects of inner classes have a reference to an object of the outer class.