Java Reference
In-Depth Information
Local inner classes
A class that is defined within a method body is called a local inner clas s, or sim-
ply a local class —yes, just as a method can have local variables, it can have
local classes. This means that the file drawer for the class is created within a
frame for a call whenever the method in which it is defined is called.
We illustrate the use of a local class with function revIt , which yields an
iterator over its parameter, array b . Thus, we show how to obtain an iterator over
any array. The outline of this method is shown in Fig. 12.20. The parameter has
modifier final for technical reasons, which we will explain later. The method is
static because it does not refer to components of the class in which it was
defined. The method is placed in a class Out simply to have a place to put it. It
could be placed in any class.
An iterator is an instance of a class that implements interface Iterator , so
we have to define that class. We place this class right in the method itself, as a
local inner class. See Fig. 12.21. The return statement of the method is then
changed to return (the name of) a new instance of local class ItOver .
We do not discuss the memory model for local inner classes here. The expla-
nation is given in a much clearer fashion than we could do here on paper, in in
activity 12-7.1 of ProgramLive .
Parameter b of method revIt must have attribute final because the value
of the parameter is being stored in a field of the local inner class —this is what
is required to allow a simple, efficient implementation.
Get this pro-
gram from les-
son page 12.6.
Activity 12-7.1
presents the
memory model
for local inner
When to use a local class
A local class LC defined in a method m can be used to:
1. Improve the structure of the program, placing LC only where it is needed.
2. Hide LC
3. Make available to LC the final parameters and local variables of m .
4. Make available to LC the components of the class in which m appears.
public static class Out {
/** = an Iterator over b's elements in reverse */
public static Iterator revIt( final Object[] b)
{ return ?; }
Figure 12.20:
Interface Iterator
Search WWH ::

Custom Search