Interview Q&A · Java · 4 questions in this topic
Local and Anonymous Inner Classes — Java Interview Q&A
Classes declared inside methods and nameless one-shot classes, and how lambdas changed their role. Part of Nested & Inner Classes · 294 questions in the Java bank.
What are method-local (local inner) classes?
Answer
A method-local class is a class declared inside a method body, so its name is visible only within that method. Its instances live only as long as the surrounding invocation needs them, and the class itself cannot be referenced from outside. This shape suits a small helper that is too specific to deserve a member-level type.
Key points
- 1Declared inside a method; usable only after the declaration in that method.
- 2Invisible outside the method, which keeps the API surface small.
- 3Can use outer instance members plus effectively final locals.
What are anonymous inner classes?
Answer
An anonymous inner class is a nameless class that is declared and instantiated in one new expression, usually to supply a one-shot implementation of an interface or a subclass. The compiler emits it as a separate class file named like Enclosing$1.class. Since Java 8, lambdas and method references have largely replaced anonymous classes for functional interfaces, though they are still needed for multi-method types.
Example
Runnable r = new Runnable() { public void run() { System.out.println("running"); } }; r.run(); // modern alternative: Runnable r2 = () -> System.out.println("running");
💡 Prefer a lambda when the target type has exactly one abstract method.
What are the restrictions on anonymous inner classes?
Answer
An anonymous class has no name, so it cannot declare its own constructors and must rely on the superclass constructor or an instance initializer. It cannot declare static members except compile-time constants, and it is single use because there is no name to reuse. Like other local classes, it can only capture local variables that are final or effectively final.
Key points
- 1No constructors: no name to give them; use an initializer block for setup.
- 2No static fields, methods, or nested types except constants.
- 3One definition plus one instance in a single expression.
- 4Only one supertype extended or implemented per anonymous class.
Does "new Runnable() {...}" instantiate an interface?
Answer
No. Interfaces are never instantiated directly in Java. That expression creates an instance of a compiler-generated anonymous class that implements Runnable, and stores it in a Runnable reference. The interface only supplies the type; the object itself belongs to the anonymous implementing class.
Example
Runnable r = new Runnable() { public void run() { } }; System.out.println(r.getClass().getName()); // shows the anonymous class, not the interface
Learn this topic
Recommended resourcesAffiliate links · may earn us a commission