Java Local inner class

A class i.e. created inside a method is called local inner class in java. If you want to invoke the methods of local inner class, you must instantiate this class inside the method.

Java local inner class example

snippet
public class localInner1{
 private int data=30;//instance variable
 void display(){
  class Local{
   void msg(){System.out.println(data);}
  }
  Local l=new Local();
  l.msg();
 }
 public static void main(String args[]){
  localInner1 obj=new localInner1();
  obj.display();
 }
}

Output:

Output
30

Internal class generated by the compiler

In such case, compiler creates a class named Simple$1Local that have the reference of the outer class.

snippet
import java.io.PrintStream;
class localInner1$Local
{
    final localInner1 this$0;
    localInner1$Local()
    {   
        super();
        this$0 = Simple.this;
    }
    void msg()
    {
        System.out.println(localInner1.access$000(localInner1.this));
    }
}
Note
Rule: Local variable can't be private, public or protected.

Rules for Java Local Inner class

Note
1) Local inner class cannot be invoked from outside the method.
Note
2) Local inner class cannot access non-final local variable till JDK 1.7. Since JDK 1.8, it is possible to access the non-final local variable in local inner class.

Example of local inner class with local variable

snippet
class localInner2{
 private int data=30;//instance variable
 void display(){
  int value=50;//local variable must be final till jdk 1.7 only
  class Local{
   void msg(){System.out.println(value);}
  }
  Local l=new Local();
  l.msg();
 }
 public static void main(String args[]){
  localInner2 obj=new localInner2();
  obj.display();
 }
}

Output:

Output
50
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents