Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of a non-final local variable within an inner class

Tags:

java

class

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.

like image 569
St.Antario Avatar asked Sep 29 '22 01:09

St.Antario


2 Answers

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; }
    }
like image 187
sol4me Avatar answered Oct 05 '22 23:10

sol4me


i is effectively final, since it is never modified. As you yourself quoted the JLS, the inner class may use effectively final variables.

like image 42
Eran Avatar answered Oct 05 '22 22:10

Eran