Why the test variable occurs compile error which inside the localClassMethod and outside the tt method,but compile is ok in tt method.
It means inner class instance variable can't mofidy the outer class instance variable,but the inner class local variable can modify the outer class instance variable.
public class Outer {
int test = 0;
void classMethod() {
class localClassInMethod {
int k = test;//compile ok
test = 1;//compile error
public void tt() {
test++;//compile ok
int m = test;//compile ok
}
}
}
}
Although the lines look similar, they are not the same:
If you want to run code to assign value
1to fieldtestwhen a new instance oflocalClassInMethodis created, use an instance initializer block:That is the same as putting the statement in every constructor: