Local inner classes in Java
When a class is defined inside a method or loop or block, it is said as local inner class. This is similar to local variables.
This can be used if a object is needed only inside a method or loop.
Scope of local class belongs to its respective function or loop in which the local class is defined.
We can access local class only within its loop or method in which it is defined.
Example
class Parents{
public static void main(String arg[]){
class Child{
int age=15;
}
Child ch=new Child();
System.out.println("Age is "+ch.age);
}
}
Output
Age is 15
We can define methods, variables, constructors except static members and methods inside a local class and can access same like every class.
We can define static variable inside local class by declaring it as constant or final only, but static methods are not allowed.
Example
class Parents{
public static void main(String arg[]){
class Child{
final static int age=15;
}
System.out.println("Age is "+Child.age);
}
}
Inheritance and interface implementation are also allowed in local classes.