«Back to Home

Core Java

Topics

Local Inner Class In Java

Local inner class

A class which is created inside the method is known as a local inner class in Java and if we want to call the methods of local inner class then we must instantiate this class inside the method.
 
In other words, when we write any class within a method and that class called as a local type such as local variables scope of the local inner class is restricted within the method (it can't be private, public or protected) and local inner classes can instantiated only in the method, where the inner class is defined in the program.
 
Let’s see an example with an instance variable, given below.
 
Code
  1. public class Tiger {  
  2.     private int age = 20;  
  3.     void display() {  
  4.         class Cub {  
  5.             void calcAge() {  
  6.                 System.out.println(age);  
  7.             }  
  8.         }  
  9.         Cub t = new Cub();  
  10.         t.calcAge();  
  11.     }  
  12.     public static void main(String args[]) {  
  13.         Tiger t1 = new Tiger();  
  14.         t1.display();  
  15.     }  
  16. }  
10
 
Output

11

In the example, mentioned above, internally the compiler generated a class, which has the reference of the outer class.
 
Some important rules are,
 
Local inner class can’t be called from outside the method in a class.
 
Local inner class can’t access non-final local variable till JDK 1.7. With JDK 1.8, it is possible to access the non-final local variable in local inner class.
 
Let’s see an example with the local variable, given below.
 
Code
  1. public class Tiger {  
  2.     private int age = 20;  
  3.     void display() {  
  4.         int tigerAge = 50//local variable must be final till jdk 1.7 only   
  5.         class Cub {  
  6.   
  7.             void calcAge() {  
  8.                 System.out.println(tigerAge);  
  9.             }  
  10.         }  
  11.         Cub t = new Cub();  
  12.         t.calcAge();  
  13.     }  
  14.     public static void main(String args[]) {  
  15.         Tiger t1 = new Tiger();  
  16.         t1.display();  
  17.     }  
  18. }  
12

In the example, mentioned above, we can see that the program gives a compile time error because we use jdk 8.0 and if we use older version of jdk, this program runs successfully.
 
Summary

Thus, we learnt that a class, which is created inside the method is known as a local inner class in Java and also learnt some important rules of Local inner class.