Search code examples
javascjp

method-local inner class cannot use variables declared within the method


Why a method-local inner class can't use variables declared inside the enclosing method except those marked final, i know that the variables declared inside the enclosing method might vanishes while the inner class instance remains valid, but what has changed when this variable/s is declared final?


Solution

  • The reason is that it is specified in the Java Language Specification #8.1.3

    Any local variable, formal parameter, or exception parameter used but not declared in an inner class must be declared final.

    Also note that project lambda (java 8), which aims at introducing closures in java (to replace anonymous classes), introduces the notion of effectively final which will allow you to use a non final variable within a lambda expression as long as you don't modify it within the closure.