Java Reference
In-Depth Information
features of member classes. It is usually more appropriate to think of them as an
entirely separate kind of nested type.
See
Chapter 5
for details as to when it's appropriate to choose
a local class versus a lambda expression.
The defining characteristic of a local class is that it is local to a block of code. Like a
local variable, a local class is valid only within the scope defined by its enclosing
block.
Example 4-3
shows how we can modify the
iterator()
method of the
LinkedStack
class so it defines
LinkedIterator
as a local class instead of a member
class.
By doing this, we move the definition of the class even closer to where it is used and
hopefully improve the clarity of the code even further. For brevity,
Example 4-3
shows only the
iterator()
method, not the entire
LinkedStack
class that
contains it.
m
e
Example 4-3. Deining and using a local class
// This method returns an Iterator object for this LinkedStack
public
Iterator
<
Linkable
>
Iterator
()
{
// Here's the definition of LinkedIterator as a local class
class
LinkedIterator
implements
Iterator
<
Linkable
>
{
Linkable
current
;
// The constructor uses a private field of the containing class
public
LinkedIterator
()
{
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
();
}
}
// Create and return an instance of the class we just defined
return
new
LinkedIterator
();
}