Java Reference
In-Depth Information
The new operator is used to create an instance of the anonymous class. It is followed by either an existing
interface name or an existing class name. Note that the interface name or class name is not the name for the newly
created anonymous class. Rather, it is an existing interface/class name. If an interface name is used, the anonymous
class implements the interface. If a class name is used, the anonymous class inherits from the class.
The <argument-list> is used only if the new operator is followed by a class name. It is left empty if the new
operator is followed by an interface name. If <argument-list> is present, it contains the actual parameter list for
a constructor of the existing class to be invoked. The anonymous class body is written as usual inside braces. The
above syntax can be broken into two for simplicity: the first syntax is used when the anonymous class implements an
interface and the second one is used when it inherits a class.
new Interface() {
// Anonymous class body goes here
}
and
new Superclass(<argument-list-for-a-superclass-constructor>) {
// Anonymous class body goes here
}
Anonymous classes are very powerful. However, its syntax is not easy to read and is somewhat unintuitive. The
anonymous class body should be short for better readability. Let's start with a simple example of an anonymous class.
You will inherit your anonymous class from the Object class, as shown:
new Object() {
// Anonymous class body goes here
}
This is the simplest anonymous class you can have in Java. It is created and it dies anonymously without making
any noise!
Now you want to print a message when an object of an anonymous class is created. An anonymous class does not
have a constructor. Where do you place the code to print the message? Recall that all instance initializers of a class are
invoked when an object of the class is created. Therefore, you can use an instance initializer to print the message in
your case. The following snippet of code shows your anonymous class with an instance initializer:
new Object() {
// An instance initializer
{
System.out.println ("Hello from an anonymous class.");
}
}
Listing 2-8 contains the complete code for a simple anonymous class, which prints a message on the standard
output.
Search WWH ::




Custom Search