J2EEOnline J2EE

Java Certification  «Prev 

Local Inner Class or Method-Local Inner Class

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();
 public static void main(String args[]){
  LocalInner1 obj=new LocalInner1();
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.

Points to Remember

The following points about local classes might come up in the OCPJP 7 exam:
  1. You can create a non-static local class inside a body of code. Interfaces cannot have local classes, and you cannot create local interfaces.
  2. Local classes are accessible only from the body of the code in which the class is defined. The local classes are completely inaccessible outside the body of the code in which the class is defined.
  3. You can extend a class or implement interfaces while defining a local class.
  4. A local class can access all the variables available in the body of the code in which it is defined.
  5. You can pass only final variables to a local inner class.

Example 2

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();
Program Output 
Within class Y
x = 3
y = 5