Java Reference
In-Depth Information
private. This is because
In
is defined in and is part of class
Out
.
4. If method
meth
is non-static, class
In
can reference all the non-static
components of class
Out
even if they are private. This is because
In
is
defined in and is part of class
Out
.
5. Inner class
In
may extend another class and implement interfaces.
In
may be extended by another class.
6. Just as local variable
local1
cannot be accessed outside of method
meth
,
class
In
cannot be accessed directly outside method
meth
.
12.4.5
Anonymous classes
We now describe the last kind of class, the
anonymous class
. An anonymous
class is a class that does not have a name. That may sound kind of silly until you
stop and think about it. Why does something have a name? Because it will be
called by that name, usually many times. If something is never called or referred
to, there is no need to give it a name. Moreover, in Java, if a class is called just
once, there is a way to write it so that the name is not necessary even then.
Consider class
Out
, of Fig. 12.21, which contains method
revIt
. Local
inner class
ItOver
is accessed in only one place, in the return statement.
Therefore, it is a candidate for becoming an anonymous class. In Fig. 12.23, to
describe most easily how to make
ItOver
into an anonymous class, we show the
class with its body replaced by <
body of class
>.
To make
ItOver
into an anonymous class (see Fig. 12.24), do the following:
1. Replace the expression after
new
by “
Iterator()
<
body of class
>”. Note
that there is no semicolon after <
body of class
> (because it ends in a
brace).
Activity
12-7.2
2. Remove the definition of class
ItOver
.
We now have an unnamed class, which implements
Iterator
.
When to use an anonymous class
Consider using an anonymous class when a class is accessed only once. But
use anonymous classes sparingly, perhaps only when the body of the class con-
tains one or two methods, because the syntax is difficult to follow. The body of
public
class Out {
void
meth(
final int
p1,
int
p2) {
final int
local1= p2;
int
local2;
public class
In { … }
}
Figure 12.22:
A local class, used to explain the rules of local classes
Search WWH ::
Custom Search