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