0

Possible Duplicate:
Java - inner class and local variables
How does marking a variable as final allow inner classes to access them?

Local Inner class can not only access the instance variables but local variables of the method (in which they are defined) as well, but the local varible has to be declared final.

Why the local variables have to declared to be final in this case?

Community
  • 1
  • 1
Ritesh Kaushik
  • 715
  • 2
  • 13
  • 24
  • More info in [my answer to this question](http://stackoverflow.com/questions/13025907/how-does-marking-a-variable-as-final-allow-inner-classes-to-access-them/13026010#13026010) – Ian Roberts Dec 08 '12 at 08:02
  • 1
    Did you not **answer** this very same question here? http://stackoverflow.com/questions/1746219/java-access-local-variables-from-anon-inner-class-priorityqueue/12144584#12144584 – The111 Dec 08 '12 at 08:22

2 Answers2

5

The reason is that an instance of the local inner class may be returned from the method and last after the method return. In such a case the local method variables won't exist while you access them.
Once you define them as final they are actually constant and therefor safe to access even afterwards. Check out cannot refer to a non final variable inside a inner class for more details.

Community
  • 1
  • 1
Avner Levy
  • 6,601
  • 9
  • 53
  • 92
4

You are talking about anonymous classes. Local variable (only) must be final to be referenced by their implementations, because the code may execute in an unknown execution frame, possibly also in another thread, so the compiler's only hope to use a value is if it's a constant at the time the anonymous class is instantiated (declared) - ie if the variable is final.

Bohemian
  • 412,405
  • 93
  • 575
  • 722