Core Java: A local class declared inside a method is visible only inside that method

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.

Code
static String describe() {
    class Local {
        String greet() { return "hello from a local class"; }
    }
    Local l = new Local();
    return l.greet();
}
System.out.println(describe());
Output
hello from a local class
Advertisement
More in JAVA

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

© Java Coding Hub · About · Contact · Privacy · Terms