Java › Inner Classes & Anonymous Classes
How would you decide between using a static nested class, a non-static inner class, a local class, an anonymous class, or a lambda expression for a given design scenario, weighing their respective trade-offs?
AdvancedAnswer
The general decision hierarchy: prefer a lambda expression whenever the target is a functional interface and the implementation is simple enough to express inline without needing additional state or methods; use an anonymous class when you need a one-off implementation of an interface with multiple methods, or need to extend a concrete/abstract class, or need access to `this` referring to the anonymous instance itself; use a local class when you need a NAMED, potentially-multiply-instantiated implementation scoped to just one method, possibly with its own constructor or multiple methods; use a non-static inner class when instances are conceptually tightly bound to a SPECIFIC outer instance and genuinely need ongoing access to that instance's state across the inner class's own lifetime (like the Iterator pattern); and default to a static nested class (Effective Java's general recommendation) whenever the nested class doesn't actually need outer-instance access at all, avoiding the unnecessary implicit reference and its associated minor memory/leak-risk overhead.
// Decision examples illustrating the hierarchy:
Runnable simple = () -> System.out.println("quick task"); // lambda: simple, functional interface
Comparator<String> cmp = new Comparator<String>() { /* multi-method or needs 'this' */ }; // anonymous: more complex
// local class: named, reusable within one method, possibly with its own constructor
// non-static inner class: Iterator pattern, needs access to outer's private state across its lifetime
// static nested class: a Node in a linked structure, no outer-instance access needed at allReal-world example A code review checklist for choosing the right nested-type construct guides a team through exactly this decision hierarchy, resulting in a codebase where lambdas dominate for simple functional interface implementations, static nested classes are the default for internal data structures, and non-static inner classes are reserved specifically for genuine outer-instance-coupled use cases like iterators.