A class declared inside a method body exists only for the duration of that call and cannot be referenced from outside it, making it useful for a small helper type needed in one place.
static String describe() {
class Local {
String greet() { return "hello from a local class"; }
}
Local l = new Local();
return l.greet();
}
System.out.println(describe());
hello from a local class
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-09-27