Java Reference
In-Depth Information
Anonymous Classes
If you wish to create an object but have no need to name the object's class, then you
can embed the class definition inside the expression with the
new
operator. These
sorts of class definitions are called
anonymous
classes
because they have no class
name. An expression with an anonymous class definition is, like everything in Java,
inside of some class definition. Thus, an anonymous class is an inner class. Before we
go into the details of the syntax for anonymous classes, let's say a little about where
one might use them.
The most straightforward way to create an object is the following:
anonymous
class
YourClass anObject =
new
YourClass();
If
new
YourClass()
is replaced by some expression that defines the class but does not
give the class any name, then there is no name
YourClass
to use to declare the variable
anObject
. So, it does not make sense to use an anonymous class in this situation.
However, it can make sense in the following situation:
SomeOtherType anObject =
new
YourClass();
Here
SomeOtherType
must be a type such that an object of the class
YourClass
is also
an object of
SomeOtherType
. In this situation you can replace
new
YourClass()
with
an expression including an anonymous class instead of
YourClass
. The type
SomeOtherType
is usually a Java interface.
Here's an example of an anonymous class. Suppose you define the following
interface:
public interface
NumberCarrier
{
public void
setNumber(
int
value);
public int
getNumber();
}
Then the following creates an object using an anonymous class definition:
NumberCarrier anObject =
new
NumberCarrier()
{
private int
number;
public void
setNumber(
int
value)
{
number = value;
}
public int
getNumber()
{
return
number;
}
};