Java Reference
In-Depth Information
The part in the braces is the same as the part inside the main braces of a class
definition. 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 as follows, may seem strange:
new
NumberCarrier()
The
new
is sensible enough but what is the point of
NumberCarrier()
? It looks like
this is an invocation of a constructor for
NumberCarrier
. But,
NumberCarrier
is an
interface and has no constructors. The meaning of
new NumberCarrier()
is simply
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 definitions.
For completeness, we have also repeated the definition of the
NumberCarrier
interface
in this display.
Display 13.11
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)