Search code examples
javamethodslocalinner-classesfinal

Why was it made possible from JDK 8 that a local inner class (inside a method) can access the non-final local variables of the enclosing method?


class Outer
{
    public void method1()
    {
        int x = 10;
        class Inner
        {
            public void inMethod()
            {
                System.out.println(x);
            }
        }
        Inner i  = new Inner();
        i.inMethod();
    }
    
    public static void main(String[] args)
    {
        Outer obj = new Outer();
        obj.method1();
    } 
}

I have gone through a few questions on StackOverflow, even those didn't have precise answers. Method local inner class - can access non final local variable


Solution

  • Well, x is not marked as final but it is effectively-final. If you add x += 5; below int x = 10; it will not longer work, because the variable is not effectively final anymore. https://www.baeldung.com/java-effectively-final

    I guess this was mainly changed/implemented that way to better support lambdas. Imagine you would have to always mark a variable final if you wanted to use it inside a lambda.