An anonymous inner class is a form of inner class that is declared and instantiated with a single statement. As a consequence, there is no name for the class that can be used elsewhere in the program; i.e. it is anonymous.
Anonymous classes are typically used in situations where you need to be able to create a light-weight class to be passed as a parameter. This is typically done with an interface. For example:
public static Comparator<String> CASE_INSENSITIVE =
new Comparator<String>() {
@Override
public int compare(String string1, String string2) {
return string1.toUpperCase().compareTo(string2.toUpperCase());
}
};
This anonymous class defines a Comparator<String>
object (CASE_INSENSITIVE
) that compares two strings ignoring differences in case.
Other interfaces that are frequently implemented and instantiated using anonymous classes are Runnable
and Callable
. For example:
// An anonymous Runnable class is used to provide an instance that the Thread
// will run when started.
Thread t = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Hello world");
}
});
t.start(); // Prints "Hello world"
Anonymous inner classes can also be based on classes. In this case, the anonymous class implicitly extends
the existing class. If the class being extended is abstract, then the anonymous class must implement all abstract methods. It may also override non-abstract methods.
An anonymous class cannot have an explicit constructor. Instead, an implicit constructor is defined that uses super(...)
to pass any parameters to a constructor in the class that is being extended. For example:
SomeClass anon = new SomeClass(1, "happiness") {
@Override
public int someMethod(int arg) {
// do something
}
};
The implicit constructor for our anonymous subclass of SomeClass
will call a constructor of SomeClass
that matches the call signature SomeClass(int, String)
. If no constructor is available, you will get a compilation error. Any exceptions that are thrown by the matched constructor are also thrown by the implicit constructor.
Naturally, this does not work when extending an interface. When you create an anonymous class from an interface, the classes superclass is java.lang.Object
which only has a no-args constructor.