VOOZH about

URL: https://www.geeksforgeeks.org/java/local-inner-class-java/

⇱ Local Inner Class in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Local Inner Class in Java

Last Updated : 27 Jan, 2026

A Local Inner Class in Java is a class defined inside a method, a constructor, or a block and is used only within that limited scope. It improves encapsulation and helps keep logic close to where it is used.

  • Declared inside a method, constructor, or block; scope is limited to that block
  • Can access outer class members and final / effectively final local variables
  • Cannot use access modifiers (public, private, protected)
  • Cannot have static members (except static final constants)
👁 nested_classes
Classification of Nested Classes

Syntax

class Outer {
void display() {
class LocalInner {
void show() {
System.out.println("Inside Local Inner Class");
}
}
LocalInner obj = new LocalInner();
obj.show();
}
}

Explanation:

  • class LocalInner: Declares a local inner class inside the display() method. Its scope is limited to this method only.
  • void show(): A method defined inside the local inner class.
  • LocalInner obj = new LocalInner(); : Creates an object of the local inner class within the same method.
  • obj.show(); :Calls the method of the local inner class.

Output
x = 10
y = 20

Explanation:

  • LocalInner is declared inside the outerMethod() method.
  • It accesses the instance variable x of the outer class.
  • It also accesses the local variable y, which is effectively final.
  • The local inner class cannot be accessed outside outerMethod().

When to Use Local Inner Class

  • When a class is required only within a single method.
  • When implementing complex logic locally without exposing it to the rest of the program.
  • As an alternative to anonymous inner classes when more structure is needed.

Note: Local inner classes are often replaced with lambda expressions in modern Java when implementing functional interfaces, but they are still important for understanding Java’s inner class concepts.

Comment
Article Tags:
Article Tags: