Anonymous classes
An anonymous class is a one-off class declared at the new expression. It has no name. You use it to implement an interface or subclass a type in a single place.
Detailed Explanation
Sometimes you need an object that implements Comparator or Runnable and you will never reuse the type. Naming a ByLengthComparator class is ceremony. An anonymous class writes the override at the call site: new Comparator<String>() { ... }.
The expression new Type() { body } does two things. It declares a class that extends Type (or implements it, if Type is an interface) and immediately constructs one instance. You can pass constructor arguments after the type name when subclassing a class. You cannot declare a constructor in the body. Instance initializer blocks stand in if you must run extra setup.
Anonymous classes are inner classes. They capture the enclosing instance if they appear in an instance context, and they capture effectively final locals. That capture is why a listener created in a method can still read the name parameter after the method returns, and why the compiler rejects later assignments to name.
Java 8 lambdas replaced the most common anonymous classes: those that implement a functional interface and contain one method. list.sort((a, b) -> a.length() - b.length()) is the same idea with less syntax. Lambdas do not introduce a new this; this inside a lambda is the enclosing class. Inside an anonymous class, this is the anonymous instance. That difference matters when you pass this to a listener registration.
You still need an anonymous class when you must implement more than one method, extend a class rather than an interface, declare extra fields, or use this as the implementation instance. new Thread() { public void run() { ... } } is an example that a lambda on new Thread(runnable) usually expresses better.
The cost is a generated class file (Outer$1.class) and heavier bytecode than a lambda. Overuse at many call sites clutters stack traces with numbered types. Prefer a named class when the behaviour has a name worth saying, and a lambda when the interface has one abstract method.
Code Examples
import java.util.Arrays;
import java.util.Comparator;
public class ByLength {
public static void main(String[] args) {
String[] names = {"cy", "ana", "bo"};
// Anonymous class: a Comparator used only here.
Arrays.sort(names, new Comparator<String>() {
@Override
public int compare(String a, String b) {
return Integer.compare(a.length(), b.length());
}
});
System.out.println(Arrays.toString(names)); // prints: [cy, bo, ana]
}
}public class Capture {
static Runnable greet(String name) {
// 'name' is effectively final, so the anonymous class may read it.
return new Runnable() {
@Override
public void run() {
System.out.println("hi " + name);
}
};
}
public static void main(String[] args) {
greet("Ira").run(); // prints: hi Ira
}
}Common Gotchas
`this` inside the body is the anonymous instance
to call an enclosing instance method that was hidden, write `Outer.this.method()`.
Lambdas are usually better for one method
they capture `this` from the enclosing class and generate less class-file noise.
Locals must be effectively final
assigning `name = name.trim()` after the anonymous class is created is a compile error.
An instance-context anonymous class pins the outer object
creating one in an instance method and storing it globally can leak the outer instance.