SHARE
Java Local Nested Class

Local Nested Class Introduction

We have previously discussed about normal inner class that is member nested class. In this post we are going to discuss about Local Nested Class in Java.

A class defined inside a block is Local Nested Class. Block here means a method, static block or initialiser block. This act almost same as an Local variable to method enclosing it. It is visible only inside the scope defined by its enclosing block. Local Nested Classes are least populer kind of nested classes in java. We use Method Local Nested Classes to achieve method specific repeated functionality.

Some points about Local Nested Classes

  • Local nested class is type of Nested class hence can access any member of the enclosing class, even the private ones.
  • It is visible only within method enclosing it, because of its limited scope.
  • We can define local Nested class inside static or non-static methods.
  • If we define class inside static method, then inner class can access only static member of the outer class, not the instance members.
  • These class cannot access any local variable except the final ones.
  • We cannot make be public, private, protected or static since it is similar to local variable
  • Local classes can not contain static fields and methods but it may contain a field which is static and final.
  • You can not define Interface inside methods, but we can define abstract classes.
  • It cannot have same name as its enclosing class.

 Example:

Example consist of two classes. One is that contain Local Nested Class.
DemoLocal.java

and Another is main class for the project.

InnerClassMain.java

Output:

As expected output will be

120
12.0
null

Local Nested Class Output
Local Nested Class Output

If you have any confusion comment down below. Happy Learning, Bye!

Facebook Comments

comments