Java local inner class
In the previous chapter we have learnt about member inner class. In this chapter we are going to learn another type of non-static nested class and static nested class.
A local Inner Class :
- Local Inner Class is not a member class of any other class.
- Its declaration is not directly within the declaration of the outer class.
- Local Inner Class can be declared inside particular block of code and its scope is within the block.
Example of the Local Inner Class :
package com.c4learn.nestedclss; class OuterClass { private int serialNo = 10; // Instance Variable void getValue() { class InnerClass { //Local Inner Class void display() { System.out.println("Sr. Number : " + serialNo); } } InnerClass ic = new InnerClass(); ic.display(); } } public class StaticNestedClassExample { public static void main(String[] args) { OuterClass m1 = new OuterClass(); m1.getValue(); } }
Explanation of the Program :
In the above program we have written the following code inside the method i.e we have declared the inner class inside the method instead of the class.
class InnerClass { //Local Inner Class void display() { System.out.println("Sr. Number : " + serialNo); } }
Thus in order to use the members of this local inner class we need to create instance of class inside same method.
InnerClass ic = new InnerClass(); ic.display();