Java Reference
In-Depth Information
Note that when a class is declared inside a method, it cannot be declared
private or static . However, the class is visible only inside of the method in
which it was declared. This makes it easier to write the class right before its
first (perhaps only) use and avoid pollution of namespaces.
An advantage of declaring a class inside of a method is that the class's
methods (in this case, compare ) has access to local variables of the function
that are declared prior to the class. This can be important in some applica-
tions. There is a technical rule: In order to access local variables, the vari-
ables must be declared final . We will not be using these types of classes in
the text.
Java also allows
class declarations
inside of methods.
Such classes are
known as local
classes and may
not be declared
with either a visibil-
ity modifier or the
static modifier.
4.8.3 anonymous classes
One might suspect that by placing a class immediately before the line of code
in which it is used, we have declared the class as close as possible to its use.
However, in Java, we can do even better.
Figure 4.44 illustrates the anonymous inner class. An anonymous class is
a class that has no name. The syntax is that instead of writing new Inner() , and
providing the implementation of Inner as a named class, we write new
Interface() , and then provide the implementation of the interface (everything
from the opening to closing brace) immediately after the new expression.
An anonymous
class is a class that
has no name.
1 class CompareTestInner3
2 {
3 public static void main( String [ ] args )
4 {
5 SimpleRectangle [ ] rects = new SimpleRectangle[ 4 ];
6 rects[ 0 ] = new SimpleRectangle( 1, 10 );
7 rects[ 1 ] = new SimpleRectangle( 20, 1 );
8 rects[ 2 ] = new SimpleRectangle( 4, 6 );
9 rects[ 3 ] = new SimpleRectangle( 5, 5 );
10
11 System.out.println( "MAX WIDTH: " +
12 Utils.findMax( rects, new Comparator<SimpleRectangle>( )
13 {
14 public int compare( SimpleRectangle r1, SimpleRectangle r2 )
15 { return r1.getWidth( ) - r2.getWidth( ); }
16 }
17 ) );
18 }
19 }
figure 4.44
Using an anonymous class to implement the function object
 
Search WWH ::




Custom Search