I will show you two code bunchs.
public class A {
int globalVariable;
public void foo() {
globalVariable++;
class B {
void foo() {
System.out.println(globalVariable);
}
}
B b = new B();
b.foo();
}
public static void main(String[] args) {
A a = new A();
a.foo();
}
}
here i declared one global variable, changed its value, declared one inner class and created instance of this class.This code will work well and print
1
Now check out this code:
public class A {
public void foo() {
int localVariable;
localVariable++;
class B {
void foo() {
System.out.println(localVariable);
}
}
B b = new B();
b.foo();
}
public static void main(String[] args) {
A a = new A();
a.foo();
}
}
i did all steps on first code except here variable is not global but local.Here i get an exception that says localVariable must be final or effectively final.I googled and understood that this is why value gets captured and passed to class.When we changed it class doesn't know about this changes and it cause confusing. i have 2 questions:
1.if it cause some confusing and we have to not change it after declaration why we don't get this exception on global variable
2.it it is about local variable value changes so we have to get this exception only if we change this value after class instance declaration.Isn't it?