Search code examples
javainner-classesfinal

Need of final variable in Inner class concept


I was practicing the Inner Class concept and inside that, Method Local Inner Class.

I know the usage of final keyword very well but in this program, I am not able to understand its significance:

//method local inner class example
package practice;

public class OuterClass 
{
    void my_Method()
    {
        final int n=23;                 //why final is required?
        class MethodInner_Demo
        {
            public void print()
            {
                System.out.println("This is method local inner class: "+n);
            }
        }
        MethodInner_Demo inner=new MethodInner_Demo();
        inner.print();
    }

    public static void main(String[] args) 
    {
        OuterClass outer=new OuterClass();
        outer.my_Method();
    }

}

And without using final, it is throwing an error in this part,

System.out.println("This is method local inner class: "+n);

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Cannot refer to the non-final local variable n defined in an enclosing scope

Please explain!

Thank you.


Solution

  • 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.

    Reference http://cs-fundamentals.com/java-programming/java-method-local-inner-classes.php