What is a local class and what is an anonymous class in Java, and how do they differ?
answer
- Both declared inside a block / method
- Local = named, reusable, can have constructors
- Anonymous = unnamed, one instance, declare+new fused
- Anonymous: one class OR one interface, never both
- Pre-lambda callback idiom
basics
~20 sA local class is a named class declared inside a method body. An anonymous class is a one-time, unnamed class you declare and instantiate in a single expression, usually to implement an interface or extend a class on the spot.
solid answer
~50 sBoth are nested classes scoped to where they are declared rather than to a package or to a top-level class body. A local class is a named class declared inside a block, typically a method body; you can instantiate it multiple times and give it constructors. An anonymous class has no name: you write `new SomeType() { ... }`, which simultaneously declares a subclass-or-implementer of SomeType and creates exactly one instance of it. So an anonymous class is essentially a local class with no name and no separate `new` step, limited to a single use. Anonymous classes can extend one class OR implement exactly one interface, but not both and not more than one. Local classes can implement interfaces and extend classes the normal way and may be reused within the method. Both can capture effectively-final local variables from the enclosing scope and access the enclosing instance's members.
go deeper
Can define both, knows local has a name and anonymous does not, and that anonymous is the old way to pass a Runnable or listener inline.
Articulates the one-class-or-one-interface limit, the no-explicit-constructor rule, and that anonymous = local class fused with a single new.
Frames the choice among lambda vs anonymous vs named local class by reuse, state, multiple methods, and readability; knows capture and this differences.
Discusses API design implications (callbacks, listeners), when forcing a named type aids debuggability and stack traces, and migration of anonymous classes to lambdas across a codebase.
## The family of Java classes Java lets you declare a class in several places. A **top-level class** lives directly in a source file. A **member class** is declared as a member of another class (a field-like position). The two kinds in this leaf live *inside a block of code* (between `{` and `}` of a method, constructor, or initializer): - **Local class** — a *named* class declared inside a block. Example: inside a method you write `class Counter { ... }`. Its name is visible only within that block, like a local variable. You then create instances with `new Counter()` as usual, possibly several times. - **Anonymous class** — an *unnamed* class that you declare and instantiate in one expression. The syntax `new Type() { /* body */ }` does two things at once: (1) it defines a brand-new class that either *extends* the class `Type` or *implements* the interface `Type`, and (2) it immediately creates exactly one object of that new class. ## Why they exist They package a small amount of behavior right where it is used, without forcing you to create a separate named top-level file. Classic use: passing a callback or a strategy. Before lambdas (Java 8), an anonymous class was the standard way to supply a `Runnable`, `Comparator`, or event listener inline. ## Key syntactic facts ```java void demo() { // local class — has a name, can be reused class Greeter { String greet(String who) { return "Hi " + who; } } Greeter g = new Greeter(); // anonymous class — no name, single instance, implements an interface inline Runnable r = new Runnable() { @Override public void run() { System.out.println("running"); } }; } ``` Note the trailing `;` after the closing brace of an anonymous class: the whole `new Type() { ... }` is an *expression* (it produces a value), so it ends with a semicolon like any statement. ## What each can and cannot do - An **anonymous class** can **extend exactly one class** *or* **implement exactly one interface** — never both, never two interfaces. It has **no name**, so it cannot declare an explicit constructor (there is no name to write a constructor for); it uses the superclass constructor via the arguments you pass in the `new Type(args) { ... }` part. - A **local class** is a normal named class, so it can implement interfaces, extend a class, and declare its own constructors. It can be instantiated multiple times. - Both can **capture** local variables that are *final or effectively final*, and both can access members of the enclosing instance. - Neither a local nor an anonymous class can declare `static` members other than constant `static final` fields (anonymous and inner local classes are not static contexts), though they may *use* static members from outside. ## Mental model Think of an anonymous class as a **local class collapsed into a single use**: take a local class, give it no name, and fuse its declaration with one `new`. If you need it more than once, or need a constructor, or need to extend a class *and* implement an interface, reach for a (named) local or member class instead. If the behavior is a single method on a functional interface, a **lambda** is usually clearer than an anonymous class.
- Can an anonymous class both extend a class and implement an interface?No. It may extend exactly one class or implement exactly one interface, but not both and not more than one. If you need that combination, declare a named (local or member) class.
- When would you prefer a lambda over an anonymous class?When the target type is a functional interface (one abstract method) and you only need to supply that one method's body with no extra state or methods. Lambdas are shorter and don't introduce a new `this`.
saying these in an interview costs you the question
- Saying an anonymous class can implement multiple interfaces
- Saying an anonymous class can have an explicit constructor
- Confusing a local class with a static nested class (local is inside a method, never static)
- Forgetting the trailing semicolon after an anonymous class body