Local Inner Class in Java
intermediate· OOP · Nested Classes
Problem
A local inner class is declared inside a method rather than at the class level, so it only exists — and can only be used — for the duration of that method call.
Define a Receipt class inside a method so it can use that method's own parameters, without existing anywhere outside it.
Input
processOrder("Notebook", 4.99)
Output
Receipt: Notebook - $4.99
Java Program
Java
public class LocalInnerClassDemo {
static void processOrder(String itemName, double price) {
// Declared entirely inside this method — unusable anywhere outside it
class Receipt {
void print() {
System.out.println("Receipt: " + itemName + " - $" + price);
}
}
Receipt receipt = new Receipt();
receipt.print();
}
public static void main(String[] args) {
processOrder("Notebook", 4.99);
}
}Output
Receipt: Notebook - $4.99
Core Logic
Declaring the Receipt class inside processOrder(), instead of as a top-level or member class, keeps it scoped to exactly the one method that needs it.
How It Works
- 1
class Receipt { ... }is written directly inside the body ofprocessOrder(), not outside it. - 2
ReceiptreadsitemNameandpricedirectly — the enclosing method's own parameters — without needing them passed in again. - 3
Receiptonly exists whileprocessOrder()is running; no code outside this method can refer to theReceipttype at all. - 4
new Receipt()andreceipt.print()use the class exactly like any other, just from within the same method it was declared in.
Calling
processOrder("Notebook", 4.99) declares Receipt, instantiates it, and prints "Receipt: Notebook - $4.99", all within that one call.💡
Key Point: The local variables a method's local class reads — like itemName and price here — have to be effectively final, since the class might reference them from a context that outlives the variable's own scope in more elaborate cases.
Key Concepts
local classmethod scopeeffectively final variables