Declaring and Instantiating Local Classes
What you'll learn: How to declare a class inside a method body and create instances of it within that same method.
The Core Idea
A local class is a class you declare inside a method, constructor, or initializer block—right where you'd normally write statements. Unlike inner classes (which belong to an instance of the outer class), local classes are declared and used entirely within a specific method's scope. You can create objects from these local classes just like any other class, but only within that method.
Think of a local class as a helper tool you build on the spot for a specific task, then leave behind when the method finishes—it exists only for that method's duration.
Declaration Syntax
Declare a local class inside a method body:
public void processData() {
class DataProcessor {
private String name;
DataProcessor(String name) {
this.name = name;
}
void process() {
System.out.println("Processing: " + name);
}
}
// Local class declared above, now instantiate it
DataProcessor processor = new DataProcessor("Report");
processor.process();
}
Instantiation
Once declared, you instantiate a local class using the normal new keyword—no special outer reference syntax needed (unlike inner classes):
public void calculate() {
class Calculator {
int add(int a, int b) {
return a + b;
}
}
Calculator calc = new Calculator();
int result = calc.add(5, 10);
}
The instance only exists within the method. Once calculate() returns, both calc and the Calculator class definition are out of scope.
Key Takeaway: Local classes are declared inside method bodies using standard class syntax and instantiated with new just like regular classes, but they exist only within the scope of the enclosing method.