Interview Q&A · Java · 4 questions in this topic

Local and Anonymous Inner Classes — Java Interview Q&A

All Java topics

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

  1. 1Declared inside a method; usable only after the declaration in that method.
  2. 2Invisible outside the method, which keeps the API surface small.
  3. 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

Example.javajava
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

  1. 1No constructors: no name to give them; use an initializer block for setup.
  2. 2No static fields, methods, or nested types except constants.
  3. 3One definition plus one instance in a single expression.
  4. 4Only one supertype extended or implemented per anonymous class.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits