Java Reference
In-Depth Information
The part in the braces is the same as the part inside the main braces of a class defi-
nition. The closing brace is followed by a semicolon, unlike a class definition. (This is
because the entire expression will be used as a Java statement.) The beginning part,
repeated below, may seem strange:
new NumberCarrier()
The
is sensible enough but what's the point of
? It looks like this
new
NumberCarrier()
is an invocation of a constructor for
. But,
is an inter-
NumberCarrier
NumberCarrier
face and has no constructors. The meaning of
is simply
new
NumberCarrier()
implements NumberCarrier
So what is being said is that the anonymous class implements the
NumberCarrier
interface and is defined as shown between the main braces.
Display 13.11 shows a simple demonstration with two anonymous class defini-
tions. For completeness we have also repeated the definition of the
NumberCarrier
interface in that display.
Display 13.1 Anonymous Classes (part 1 of 2)
This is just a toy example to
demonstrate the Java syntax for
anonymous classes.
1 public class AnonymousClassDemo
2{
3
public static void main(String[] args)
4
{
5
NumberCarrier anObject =
6
new NumberCarrier()
7
{
8
private int number;
9
public void setNumber( int value)
10
{
11
number = value;
12
}
13
public int getNumber()
14
{
15
return number;
16
}
17
};
18
NumberCarrier anotherObject =
19
new NumberCarrier()
20
{
21
private int number;
22
public void setNumber(int value)
23
{
24
number = 2*value;
25
}
(continued)
Search WWH ::




Custom Search