All 15 Inner Classes & Anonymous Classes questions
More in Inner Classes & Anonymous Classes
Advertisement
Java › Inner Classes & Anonymous Classes

How do local classes (defined within a method body) and anonymous classes differ in their capabilities and use cases, particularly regarding capturing local variables and reusability?

Advanced

Answer

A local class is defined and named within a method body, scoped entirely to that method, usable multiple times within the method and even instantiated multiple times, capturing effectively-final local variables from the enclosing method scope just as a lambda does; an anonymous class is a local class taken further -- defined and instantiated in a single expression with no name at all, typically used for a genuinely one-off implementation of an interface or abstract class needed at exactly one usage site -- both can access effectively-final local variables and the enclosing instance's members, but a local class's ability to be named and reused (potentially instantiated multiple times, or having multiple methods beyond the single abstract method an anonymous class implementing a functional interface would have) makes it more suitable when you need more than a single-use, single-method implementation.
public List<Runnable> createTasks(int count) {
    List<Runnable> tasks = new ArrayList<>();
    class NamedTask implements Runnable {  // local class -- named, reusable within this method
        private final int id;
        NamedTask(int id) { this.id = id; }
        public void run() { System.out.println("Task " + id); }
    }
    for (int i = 0; i < count; i++) {
        tasks.add(new NamedTask(i));  // instantiated multiple times, unlike a typical anonymous class use
    }
    return tasks;
}
Real-world example A method needing to create several distinct task instances (each with its own constructor-supplied ID) within a single method body uses a local class rather than several separate anonymous classes, since the local class can be instantiated repeatedly with different constructor arguments, something a single anonymous class expression can't directly provide.

Common follow-ups: Why might a local class be preferred over a private nested class if it's genuinely only used within one specific method?;How do local classes interact with generic type parameters from their enclosing method?