JLS 8.1.3 gives us the rule about variables which are not declared in an inner class but used in the class.
Any local variable, formal parameter, or exception parameter used but not declared in an inner class must either be declared final or be effectively final (§4.12.4), or a compile-time error occurs where the use is attempted.
An example:
class A{
void baz(){
int i = 0;
class Bar{ int j = i; }
}
public static void main(String[] args){
}
}
DEMO
Why was the code compiled? We used the non-final local variable in the inner class which was no declared in there.
Variable i
defined inside method baz is effictively final because value of variable i is not modified elsewhere. If you change it
void baz(){
int i = 0;
i = 2;
class Bar{ int j = i; }
}
The code will fail to compile because variable i
is no longer effictively final but if you just declare the variable i and the initialize it in another line, the code will compile because the variable is effictively final
void baz(){
int i;
i = 2;
class Bar{ int j = i; }
}
i
is effectively final, since it is never modified. As you yourself quoted the JLS, the inner class may use effectively final variables.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With