Java Reference
In-Depth Information
The local class
MyIntHolder
is sometimes called a
closure
. In
more general Java terms, a closure is an object that saves the
state of a scope and makes that scope available later.
Closures are useful in some styles of programming, and different programming lan‐
guages define and implement closures in different ways. Java implements closures as
local classes, anonymous classes, and lambda expressions.
Anonymous Classes
An
anonymous class
is a local class without a name. It is defined and instantiated in
a single succinct expression using the
new
operator. While a local class definition is a
statement in a block of Java code, an anonymous class definition is an expression,
which means that it can be included as part of a larger expression, such as a method
call.
m
e
For the sake of completeness, we cover anonymous classes
here, but for most use cases in Java 8 and later, lambda expres‐
sions (see
“Conclusion” on page 174
) have replaced anony‐
mous classes.
Consider
Example 4-5
, which shows the
LinkedIterator
class implemented as an
anonymous class within the
iterator()
method of the
LinkedStack
class. Compare
it with
Example 4-4
, which shows the same class implemented as a local class.
Example 4-5. An enumeration implemented with an anonymous class
public
Iterator
<
Linkable
>
iterator
()
{
// The anonymous class is defined as part of the return statement
return
new
Iterator
<
Linkable
>()
{
Linkable
current
;
// Replace constructor with an instance initializer
{
current
=
head
;
}
// The following 3 methods are defined by the Iterator interface
public
boolean
hasNext
()
{
return
current
!=
null
;
}
public
Linkable
next
()
{
if
(
current
==
null
)
throw
new
java
.
util
.
NoSuchElementException
();
Linkable
value
=
current
;
current
=
current
.
getNext
();
return
value
;
}
public
void
remove
()
{
throw
new
UnsupportedOperationException
();
}
};
// Note the required semicolon. It terminates the return statement
}