Using a non-finite local variable inside an inner class

JLS 8.1.3 gives us a rule about variables that are not declared in the inner class, but are used in the class.

Any local variable, formal parameter, or exception parameter is used, but not declared in the inner class, must either be declared final or be (ยง4.12.4), or a compile-time error occurs when an attempt is used.

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 a non-finite local variable in an inner class that was not declared there.

+5
source share
3 answers

The variable i , defined inside the baz method, is finally final, because the value of the variable i does not change elsewhere. If you change it

 void baz(){ int i = 0; i = 2; class Bar{ int j = i; } } 

The code will not compile because the variable i ceases to be finally final, but if you just declare the variable i and initialize it on a different line, the code will be compiled because the variable is finally final

  void baz(){ int i; i = 2; class Bar{ int j = i; } } 
+2
source

i is actually final, since it never changes. As you yourself quoted JLS, an inner class can use final variables efficiently.

+1
source

Because i is actually final, as it is not changed in baz .

+1
source

Source: https://habr.com/ru/post/1210716/


All Articles