Anonymous Classes in Java
An anonymous class defines and instantiates a one-off subclass or interface implementation in a single expression, with no separate named class declaration at all — new Runnable() { public void run() { ... } } creates an object implementing Runnable right on the spot, supplying its method body inline. It exists specifically for cases where a class is only ever going to be used once, right there, and giving it a real name elsewhere in the codebase would add a small file or declaration with no real reuse value.
Since Java 8, a lambda expression can replace an anonymous class specifically when implementing a functional interface — one with exactly one abstract method — which covers the large majority of anonymous classes seen in older code. Anonymous classes are still needed for interfaces with more than one abstract method, or for extending an actual class rather than implementing an interface.
The syntax
new InterfaceOrClass() { ... } both defines and instantiates a one-off implementation in a single expression.
No separate declaration needed
The anonymous class exists only at that point in the code, with no name to reference elsewhere.
Implementing an interface anonymously
The braces supply a full implementation of the interface's method or methods, right inline.
Extending a class anonymously
The same syntax can also create a one-off subclass of a real class, overriding whichever methods are needed.
Lambdas replace many anonymous classes
But only for functional interfaces with exactly one abstract method; multi-method interfaces and class extension still need the full anonymous-class syntax.
public class AnonymousDemo { interface Greeting { void sayHello(); } public static void main(String[] args) { Greeting g = new Greeting() { public void sayHello() { System.out.println("Hello from an anonymous class"); } }; g.sayHello(); }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.