Local Inner Class Tutorial

The local inner class is one of the four nested classes that I briefly discussed in my Introduction to Nested Classes tutorial. A local inner class, aka method-local inner class is defined inside of a method.
class Standard {
     String instanceVar = "";
     void methodName(String params) {
         String s = "";
         class LocalInner {
             int i = 0;
         }
     }
}

The first thing to understand about a local inner class is that it can only be instantiated from within the method that it is contained in. You cannot create an instance of the class anywhere else.

Here are some rules for a local inner class:

  • A local inner class has complete access to all the members of the class that it is inside of.
  • A local inner class does not have access to the local variables of the method that it is inside of unless those variables are marked final or they are effectively final.
  • You cannot specify an access modifier.
  • You can specify abstract or final - who knows why you would want to, but you can.
  • You cannot mark the class static, and you may not have static variables or methods inside of the class.
  • The local class definition must be defined in your code prior to attempting to create an instance.



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md LocalInnerClass
C:\Java>cd LocalInnerClass
C:\Java\LocalInnerClass>Notepad LocalInnerClass.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


class Tester {
    public static void main(String args[]) {
        Outer outer = new Outer();
        outer.displayST();
    }
}

class Outer {
    String s = "outer s";
    
    void displayST() {
        String t = "method t";
        System.out.println(s + ", " + t);

        /*class LocalInner {
            int i = 41; // effectively final - Java 8
            //i++; // ruins effectively final
            void displayMessage() {
                System.out.println(s);
                System.out.println(t);
                System.out.println(i);
            }
        }
        LocalInner li = new LocalInner();
        li.displayMessage();*/
    }    
}

Now switch back to the command prompt (CMD) and type in javac LocalInnerClass.java and press Enter.
Now type in java LocalInnerClass and press Enter.


C:\Java\LocalInnerClass>javac LocalInnerClass.java
C:\Java\LocalInnerClass>java LocalInnerClass
outer s, method t;

outer s, method t, 41


Final thoughts

The most important thing to remember about a local inner class is that it can only be instantiated from within the method that it is contained in.


Tutorials