Method Local Inner Classes in Java

Method Local Inner Classes in Java

Local inner classes are local to code blocks, such as a method body, constructor, or initialization block and can be used within the same code block they were defined in.

Local inner classes also called method local inner classes are not members of the class of which the code is a part but are local to the code block they belong to, just as a local variable. Local inner classes cannot be accessed outside the block in which they are defined. Instances of local inner classes are normal objects that can be passed as arguments and returned from methods, and they exist within a valid scope. For local inner classes are local to a code block, they cannot have access modifiers. Also, local inner classes cannot be declared static because they are local. For local inner classes only strictfp and annotations are practical applications. Throughout this tutorial the two terms local inner class and method local inner class will be used interchangeably.

Scope and use of Method Local Inner Class

Because a method local inner class is defined within a method, it can only be instantiated within from the method. No other code outside the method can instantiate local inner class.

Important point to note is like regular inner class objects, the method local inner class object shares a special relationship with the enclosing class object, and can access outer class's private members as regular inner classes do. But the local inner class object cannot use the local variables of the method in which the local inner class is defined.

The reason why method local inner class cannot use local variables of the method is the local variables of the method are kept on the stack and perish as soon as the method ends. But even after the method ends, the local inner class object may still be alive on the heap. Method local inner class can still use the local variables that are marked final, any idea why? James Gosling states the following reason in his famous book "The Java Programming Language, Fourth Edition"

In the local inner class the only restriction is that a local variable or method parameter can be accessed only if it is declared final. The reason for this restriction relates mainly to multi-threading issues and ensures that all such variables have well-defined values when accessed from the local inner class. Given that the method accessing the local variable or parameter could be invoked after the completion of the method in which the local inner class was defined and hence the local variables and parameters no longer exist the value of those variables must be frozen before the local inner class object is created. If needed, you can copy a non-final variable into a final one that is subsequently accessed by the local inner class.

The following piece of code demonstrates you the scope and use of method local inner class. Though the given piece of code will not compile unless you comment or remove System.out.println(y); statement. It is because local inner class cannot access the method's local variable unless they are declared final.

/* MethodLocalInnerClassDemo.java */
 
class MyOuter
{
    private int x = 10;
 
    public void createLocalInnerClass()
    {
        int y = 20;
        final int z = 30;
        class LocalInner 
        {
            public void accessOuter()
            {
                System.out.println(x);
                System.out.println(y); //Error: Cannot refer to a non-final variable y inside an inner class defined in a different method.
                System.out.println(z);
            }
        }
 
        LocalInner li = new LocalInner();
        li.accessOuter();
    }
}
 
public class MethodLocalInnerClassDemo
{
    public static void main(String[] args)
    {
        MyOuter mo = new MyOuter();
        mo.createLocalInnerClass();
    }
}

Local Inner Classes in Static Context

A local inner class shares a special relationship with the enclosing class therefore it is associated with an instance of the enclosing class. It is possible to declare a local inner class, or an anonymous inner class, in a static context: within a static method, a static initialization block, or as part of a static initializer. In these static contexts there is no corresponding instance of the enclosing class, and so the local inner class instance has no enclosing class instance. In these circumstances, any attempt to use a qualified-this expression to refer to an enclosing class's instance fields or methods will result in a compile-time error.

Last Word

It is significant to note that a method local inner class cannot be marked public, private, protected, static, or transient. Because it is by default local to a method. The only modifiers you can apply to a method local inner class are abstract and final, but never both at the same time; else your local inner class will be of no use.

In this tutorial we talked of local inner class or method local inner class. A local inner class can also be defined in static code block but will result into compile time error if it tries to access non-static members of enclosing class. Local inner class have limited scope till the block in which the class is defined. Hope you have enjoyed reading this tutorial. Please do write us if you have any suggestion/comment or come across any error on this page. Thanks for reading!

References



Share this page on WhatsApp

Get Free Tutorials by Email

About the Author

is the founder and main contributor for cs-fundamentals.com. He is a software professional (post graduated from BITS-Pilani) and loves writing technical articles on programming and data structures.