简体   繁体   中英

Usage of a non-final local variable within an inner 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.

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.

因为ibaz没有改变,所以i实际上是最终的。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM