What is the internal reason due to which within method local inner class we can only access final or effectively final local variables of the method in which that inner class is declared? Please see below example.
class Test{
int i = 10;
static int j = 20;
public void m1(){
int k = 30;
//k=40;
final int m = 40;
class Inner{
public void m2(){
System.out.println("value of i = " + i + " value of j = " + j + " value of k = " + k + " value of m = " + m);
}
}
Inner i = new Inner();
i.m2();
}
public static void main(String[] args){
Test t = new Test();
t.m1();
}
}
If I try to change the value of variable k
(line commented in source code), then there will be compiler error stating "local variables referenced from an inner class must be final
or effectively final
"
Also in java versions lower than 1.8, local variables must be explicitly defined as final if you want to access that variable within method local inner class.