As the name suggests, a local inner class is a class that you define within a method or a scope block of another class. Unlike member inner classes, you can only access local inner classes within the method or block where they are defined. They primarily serve for ‘Encapsulation’, where you require a class for a specific method and do not want it to be accessible outside of that method. Local inner classes provide a means to logically group classes within methods, enhancing code organization and readability.
Enhancing Functionality with Local Inner Class
To use a local inner class, you define it within a method or a block using the class keywords. You can instantiate object of the local inner class within the same method or block.
Syntax:
public class OuterClass{ void someMethod(){ class LocalInner{ // Class body } } }
Access Modifier:
Local inner classes can’t have access modifier like ‘public’, ‘private’, or ‘protected’. They are only accessible within the block in which they are define.
Usage of static, final, super, this:
Local inner classes can’t use static variables or methods, but they can access final variables from the surrounding block. They can’t use ‘super’ to refer to the outer block, but they can use ‘this’ to refer to themselves.
Example:
public class OuterClass { private int outerData = 10; public void outerMethod() { int localVar = 5; class LocalInner { void display() { System.out.println("Outer Data: " + outerData); System.out.println("Local Variable " + localVar); } } // Instantiate and use LocalInner class LocalInner inner = new LocalInner(); inner.display(); } public static void main(String args[]) { OuterClass outer = new OuterClass(); outer.outerMethod(); } }
Explanation:
This example shows how a class called ‘OuterClass’ has a method named ‘outerMethod()’. Inside this method, there’s a special kind of class called ‘LocalInner’. This ‘LocalInner’ class has a function called ‘display()’ that shows the values of ‘outerData’ and ‘localVar’. When we run the main part of the code, it creates an object of ‘OuterClass’ and calls its ‘outerMethod()’. This method, in turn, makes a new object of ‘LocalInner’ and uses its ‘display()’ function to show the values we mentioned.
Output: Outer Data: 10 Local Variable: 5