A class that is created inside a method is known as a
local inner class.
If you want to invoke the methods of local inner class, you must instantiate this class inside the method.
public class LocalInner1{
private int data=29; //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();
}
}
A
local inner class is defined in a code block (say, in a method, constructor, or initialization block).
Unlike
static nested classes and inner classes, local inner classes are not members of an outer class; they are just local to the method or code in which they are defined.
Here is the general syntax of a local class:
class TestClass {
void someFunction() {
class Local { }
}
}
As you can see in this code, Local is a class defined within someFunction. It is not available outside of someFunction, not even to the members of the TestClass.
Since you cannot declare a local variable static, you also cannot declare a local class static. Since you cannot define methods in interfaces, you cannot have local classes or interfaces inside an interface. In addition, you cannot create local interfaces. In other words, you cannot define interfaces inside methods, constructors, and initialization blocks.
One thing you need to remember about
local classes is that you can only pass
final variables to a local class.
package com.java.localinner;
public class X {
public void someMethod(){
class LocalInner{
int x = 3,y = 5;
public void accessX(){
System.out.println("x = " + x);
System.out.println("y = " + y);
}
}
LocalInner li = new LocalInner();// instance of LocalInner is created
li.accessX(); // method within LocalInner is called
}
protected class Y{
public void printText(){
System.out.println("Within class Y");
}
}
public static void main(String[] args) {
X x1 = new X();
X.Y y1 = x1.new Y();
y1.printText();
x1.someMethod();
}
}
/*
Program Output
Within class Y
x = 3
y = 5
*/