CodeGym /Courses /JAVA 25 SELF /Local classes: declaring inside methods

Local classes: declaring inside methods

JAVA 25 SELF
Level 16, Lesson 3
Available

1. Local class

A local class is a class declared inside a method (or even inside a code block, for example, in a loop or in an if block). It is visible and accessible only within that method, and outside of it — as if it never existed. Unlike anonymous classes, a local class has a name (albeit a simple one), can contain several methods, and even fields.

By analogy — imagine you’re cooking a complex dish by a recipe. In one of the steps you need to prepare a special sauce that is used only in this recipe and nowhere else. Instead of publishing a separate cookbook for a single sauce, you just describe how to make it right inside the main recipe. A local class works the same way — it’s “a recipe within a recipe,” needed only in one specific method.

Example of declaring a local class

public class Outer {
    void someMethod() {
        class Local {
            void print() {
                System.out.println("Hello from Local!");
            }
        }
        Local local = new Local();
        local.print();
    }
}

Here the Local class is declared inside the someMethod method of the Outer class. It exists only in this method and is not visible from the outside.

Syntax of local classes

The declaration of a local class is similar to a regular class declaration, except it happens inside a method:

void myMethod() {
    class MyLocalClass {
        void doSomething() {
            System.out.println("The local class is working!");
        }
    }

    MyLocalClass obj = new MyLocalClass();
    obj.doSomething();
}

Syntax features:

  • A local class can be declared inside any method, constructor, or even an initializer block.
  • A local class must have a name (unlike anonymous classes).
  • A local class cannot be declared with access modifiers (public, private, protected) or with the static modifier.
  • A local class can implement interfaces or extend other classes.

Comparison of class types:

public class Example {
// 1. Regular class (in a separate file)
// class RegularClass { ... }

    // 2. Inner class (inside a class)
    class InnerClass { }
    
    // 3. Static nested class (inside a class)
    static class NestedClass { }
    
    void method() {
        // 4. Local class (inside a method)
        class LocalClass { }
        
        // 5. Anonymous class (inside a method, without a name)
        Object obj = new Object() { };
    }
}

Local class = a named class intended only for this method!

2. Features of local classes

Access to method variables

A local class can access:

  • Fields of the outer class (even if they are private).
  • Only final or effectively final variables of the enclosing method.

What is “effectively final”?
It’s a variable whose value does not change after initialization. For example:

void foo() {
    int x = 5; // effectively final
    class L { void print() { System.out.println(x); } }
}

If you later wrote x = 10;, the compiler would complain.

Why is that?

This is related to how Java implements local classes under the hood: method variables are effectively copied into the local class rather than stored by reference. If a variable could change, the local class might work with an outdated copy — a path to bugs and headaches.

Example with access to variables

public class Outer {
    private String secret = "secret!";

    void revealSecret() {
        String greeting = "Hello,"; // effectively final

        class Revealer {
            void printSecret() {
                System.out.println(greeting + " " + secret);
            }
        }

        Revealer revealer = new Revealer();
        revealer.printSecret();
    }
}

3. Using local classes: why and when?

Local classes are not for everyday use, but sometimes they make code cleaner and more compact. Here’s when you should use them:

  • Helper logic specific to a single method.
    For example, if a method needs to implement complex sorting, filtering, or a temporary data structure.
  • Encapsulation to avoid “polluting” a class with extra types.
    If a class is needed only in one place, why make it visible throughout the class or package?
  • Implementation of design patterns where helper objects are needed only locally.

Example: sorting using a local class

Suppose you have a list of names and you want to sort them by length. You can create a local comparator class:

import java.util.*;

public class NameSorter {
    public void sortNames(List<String> names) {
        class LengthComparator implements Comparator<String> {
            @Override
            public int compare(String a, String b) {
                return Integer.compare(a.length(), b.length());
            }
        }
        Collections.sort(names, new LengthComparator());
    }
}

Example: a temporary structure

Sometimes you need to create a helper structure to process data in a single method:

void processScores(int[] scores) {
    class ScoreInfo {
        int score;
        boolean passed;

        ScoreInfo(int score) {
            this.score = score;
            this.passed = score >= 60;
        }
    }

    for (int s : scores) {
        ScoreInfo info = new ScoreInfo(s);
        System.out.println("Score: " + info.score + ", passed: " + info.passed);
    }
}

4. Local classes vs. anonymous classes

Sometimes the question arises: why do we need local classes at all if we have anonymous ones? Let’s figure it out.

  • Local class — a named class that you can use multiple times in a method, add fields, multiple methods, nested classes.
  • Anonymous class — a one-off implementation of an interface or a subclass, without a name, usually with one method (or overriding one or two methods).

When to use:

  • If the logic is simple and needed only once — use an anonymous class.
  • If you need more methods or fields, or the class will be used in several places in the method — use a local class.

Example comparison

Anonymous class:

Runnable r = new Runnable() {
    @Override
    public void run() {
        System.out.println("Quick and anonymous!");
    }
};

Local class:

void doWork() {
    class MyWorker implements Runnable {
        @Override
        public void run() {
            System.out.println("I'm a local class!");
        }
    }
    MyWorker worker = new MyWorker();
    worker.run();
}

5. Limitations and features of local classes

  • Access modifiers: A local class cannot be declared as public, private, or protected. You also cannot add static.
  • Static members: A local class cannot contain static members, except constants (static final).
  • Scope: A local class is visible only in the block where it is declared.
  • Using generic parameters: A local class can be generic if needed.
  • Nesting: You can declare local classes inside other local classes (but don’t overuse it, or your code will start to look like a matryoshka doll).

6. Local classes in a real application

Let’s continue developing our training application. Suppose we have a Quiz class that asks the user questions and checks answers. We want to create a temporary class inside the checking method that will store the user’s answer and the verification status.

Example: using a local class in an application

import java.util.Scanner;

public class Quiz {
    private String question = "Capital of France?";
    private String correctAnswer = "Paris";

    public void runQuiz() {
        Scanner scanner = new Scanner(System.in);

        System.out.println(question);
        String userAnswer = scanner.nextLine();

        // Local class for storing the result
        class AnswerResult {
            String answer;
            boolean isCorrect;

            AnswerResult(String answer) {
                this.answer = answer;
                this.isCorrect = answer.equalsIgnoreCase(correctAnswer);
            }

            void printResult() {
                if (isCorrect) {
                    System.out.println("Correct!");
                } else {
                    System.out.println("Incorrect, the correct answer is: " + correctAnswer);
                }
            }
        }

        AnswerResult result = new AnswerResult(userAnswer);
        result.printResult();
    }
}

Here the AnswerResult class exists only inside the runQuiz method and is not needed anywhere else. This is an excellent practical example of a local class!

7. Common mistakes when working with local classes

Error No. 1: trying to access a method variable that is not final or not effectively final.
If you declared a variable in a method and then changed its value after using it in a local class, the compiler will immediately raise an error. Always ensure such variables don’t change after initialization.

Error No. 2: wanting to add access modifiers or static.
A local class cannot be declared with the public, private, protected, or static modifiers. If you try to do this — the compiler will object.

Error No. 3: trying to use a local class outside the method.
A local class lives only in the method (or block) where it is declared. It is not accessible from other methods or from outside the class.

Error No. 4: overusing local classes for complex logic.
If your local class becomes too large, contains many methods or fields — most likely it should be extracted into a separate class. Local classes are good for compact, helper tasks.

1
Task
JAVA 25 SELF, level 16, lesson 3
Locked
Interactive bulletin board: temporary greeting 👋
Interactive bulletin board: temporary greeting 👋
1
Task
JAVA 25 SELF, level 16, lesson 3
Locked
Secret Keeper: Controlled Secret Disclosure 🔐
Secret Keeper: Controlled Secret Disclosure 🔐
1
Task
JAVA 25 SELF, level 16, lesson 3
Locked
Specialized calculator: instant sum display ➕
Specialized calculator: instant sum display ➕
1
Task
JAVA 25 SELF, level 16, lesson 3
Locked
Text Data Analyzer: brief name report 📊
Text Data Analyzer: brief name report 📊
Comments (1)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Hoist Level 1, San Diego, United States
14 May 2026
there is no book that will explain more advanced Java (or any programming language) like Codegym does -- it's the magic along with huge piles of zesty homework which is not optional ... to get good