Local Inner Class in Java

Naveen AnamaneniUpdated · 4 min read

A local class is declared inside a method (or any block), exactly like a local variable. It exists only within that block: nothing outside the method can see it or create it. It's the right tool when a helper class makes sense for one method and nowhere else. Since Java 16 you can also declare local records, enums and interfaces, which are handy for small, method-only data shapes.

A Helper That Lives in One Method

Marks.java▶ Try it
public class Marks {
    static String report(String student, int[] marks, int passMark) {
        class Subject {
            final int score;
            Subject(int score) { this.score = score; }
            boolean passed() { return score >= passMark; }
        }
 
        int passed = 0;
        for (int m : marks) {
            if (new Subject(m).passed()) {
                passed++;
            }
        }
 
        record Result(String name, int passed, int total) { }
        Result r = new Result(student, passed, marks.length);
        return r.name() + " passed " + r.passed() + " of " + r.total();
    }
 
    public static void main(String[] args) {
        System.out.println(report("Srihitha", new int[] {78, 32, 91, 40}, 35));
    }
}
Output
Srihitha passed 3 of 4

How it works

  1. class Subject is declared inside report. Its scope starts at its declaration and ends at the method's closing brace.
  2. passed() uses passMark, a parameter of the enclosing method. Local classes can read local variables and parameters that are effectively final (never reassigned).
  3. record Result(...) is a local record (Java 16). Records get their own lesson, "Records in Java"; here it just bundles three values.
  4. Scores 78, 91 and 40 pass a mark of 35; 32 doesn't.

What Local Classes Can Use

FromAllowed?
Effectively final locals and parameters of the enclosing methodYes (a copy is captured)
Locals that are reassigned anywhereNo: compile error
Instance fields of the outer object (if the method isn't static)Yes
Static members of the outer classYes
Access modifiers on the local class itself (public, private)No: it's already local

Local records, enums and interfaces are implicitly static: they can't capture local variables or the outer this, which keeps them simple.

Local Class, Anonymous Class or Lambda?

NeedChoose
A one-off implementation of a single-method interfaceA lambda
A one-off object of a class with several methodsAn anonymous class
A named helper type used several times in one methodA local class
A small data bundle inside one methodA local record

Common Mistakes

Reassigning a captured variable. Even a later passMark++ makes the earlier capture a compile error.

Putting private or public on a local class. Local classes take no access modifiers.

Using a local class from another method. It doesn't exist outside its block; move it up to the class level.

Practice

  1. Easy: Inside a method, declare a local record Item(String name, long price), create three items and print the costliest one.
  2. Harder: Write a method static int countWords(String text, int minLength) with a local class Word that knows whether it's at least minLength long. Count the qualifying words in a sentence.

Quick check: Local classes

4 questions
1Where is a local class visible?
2Which local variables can a local class use?
3Since which version are local records allowed?
4Can a local class be declared private?

Key Takeaways

Was this tutorial helpful?

Lesson 171 of 482