Java Anonymous Inner Class: Syntax, Use Cases, Limits
Learn how Java anonymous inner classes work: syntax, variable capture, memory behavior, when to use them, and how they compare with lambdas.

Java anonymous inner classes let you implement an interface or extend a class in a single expression. This article covers their syntax, variable capture, memory behavior, limitations, and how they compare with lambdas.
Syntax and Basic Usage
An anonymous inner class is declared and instantiated in a single expression, without a name. It is useful when you need a one-off implementation of an interface or a subclass of a class.
Runnable task = new Runnable() {
@Override
public void run() {
System.out.println("Running task");
}
};The expression new Runnable() { ... } defines a class that implements Runnable and immediately creates an instance. The class body can override methods and define additional members, though the variable's static type is the interface or superclass.
Because the class has no name, you cannot refer to it elsewhere in the code. The anonymous object is used through the reference produced by the expression, usually by assigning it to a variable or passing it directly to a method.
Capturing Variables and Effectively Final
Anonymous inner classes can capture local variables from the enclosing scope, but only if those variables are final or effectively final. This rule exists because the anonymous class instance may outlive the method that created it, and Java copies the captured local variable values into the anonymous class instance.
int count = 10;
Runnable task = new Runnable() {
@Override
public void run() {
System.out.println(count);
}
};If count is reassigned after being captured, the code will not compile. This is a common source of errors when converting from an anonymous class to a lambda, because lambdas have the same restriction.
Instance variables are different: they do not need to be final or effectively final. An anonymous class created in an instance context can access and mutate them because it holds an implicit reference to the enclosing object, rather than a copy of the field value.
Anonymous Inner Classes vs. Lambdas
Lambdas, introduced in Java 8, provide a more concise syntax for functional interfaces. For a single abstract method, a lambda can replace an anonymous inner class.
Runnable task = () -> System.out.println("Running task");However, the two are not always interchangeable. An anonymous inner class can implement an interface with multiple abstract methods, or extend a class. A lambda can only target a functional interface. Also, an anonymous inner class has its own this reference, while a lambda's this refers to the enclosing instance. This difference matters when you need to refer to the anonymous object itself inside its method.
For example, if you need to call a method that is defined only in the anonymous class body, you must use the anonymous class form. With a lambda, this points to the surrounding object, so the method is not found on that type.
Common Use Cases
Anonymous inner classes have long been used for event listeners, comparators, and thread tasks. For example, a button listener in Swing:
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Clicked");
}
});Before lambdas, this was the standard pattern. Even today, an anonymous inner class is useful when the interface has multiple abstract methods, such as MouseListener, or when you need to extend a class with additional behavior.
Anonymous classes also appear in older comparator code. Comparator has a single abstract method, so a lambda is cleaner in modern Java, but the anonymous form is still common in codebases that target Java 7 or earlier:
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String a, String b) {
return a.length() - b.length();
}
});Memory and Performance Considerations
Each anonymous inner class that appears in source code compiles to a separate class file. At runtime, the JVM loads that class when the code first executes, which can add memory overhead compared with a lambda. Lambda expressions use invokedynamic to link the lambda body at runtime, so they are not tied to a source-level class file in the same way.
An anonymous inner class created inside an instance method or instance initializer holds an implicit reference to the enclosing object. If the anonymous instance outlives the enclosing object, that reference can prevent garbage collection and cause a memory leak. This is especially relevant in Android activities or long-lived applications. A lambda does not capture the enclosing instance unless it refers to this or to an instance member. Anonymous inner classes declared in a static context do not capture an enclosing instance.
Limitations and When to Avoid
Anonymous inner classes cannot declare their own constructors. When you write the new expression, you can pass arguments to the constructor of the class you are extending, but you cannot add named constructor parameters. Because the class has no name, you cannot refer back to it from elsewhere to create additional instances. If the same behavior is needed in multiple places, a named class or a lambda (for functional interfaces) is usually clearer.
Another limitation is that an anonymous inner class cannot be abstract and cannot declare static members except constant variables. It can implement an interface with several abstract methods, but every method must be implemented in the anonymous body. If the body grows large, a named class is more maintainable.
If the implementation is complex or needs to be tested independently, a named inner class or a separate top-level class is a better choice. Anonymous inner classes are best for short, single-use implementations.
Anonymous Inner Classes in Modern Java
With Java 8 and later, lambdas cover most functional interface use cases. However, anonymous inner classes remain relevant for:
- Implementing an interface with multiple abstract methods.
- Extending a class with additional behavior.
- Using
thisto refer to the anonymous instance itself. - Working with legacy code that predates lambdas.
When you encounter an anonymous inner class in existing code, you can often replace it with a lambda if the target type is a functional interface. The refactoring is straightforward, but you must verify that the semantics of this and variable capture are compatible.
For instance, if the anonymous class overrides toString() or has its own fields, a lambda cannot express that. In such cases, keep the anonymous inner class or extract a named class.
Try matching browser tools
All toolsSmall utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Java guides
All Java guidesJava Final Keyword: Usage and Behavior
How Java's final keyword works for variables, methods, and classes, with practical examples and decision guidance for using it.
Java Final Variable: Syntax, Behavior, and Use Cases
Understand what a final variable in Java means, how initialization works, and when to use it for constants, immutability, and clearer code.
Java Duration vs Period: When to Use Each
java duration vs period: Compare Java Duration and Period to handle time-based and date-based calculations correctly. Learn syntax, conversion, and pitfalls.
Instance vs Static Variables in Java: Key Differences
Understand the difference between instance and static variables in Java, including memory, lifecycle, and when to use each.
More in Java
All Java guidesThe guides filed next to this one in Java, in library order.