3 ms·
If it's not static you wouldn't be able to reference it from the static context (the inner class baz). It could be non-final though, because it's a field not a
by spacemanaki 15y ago
If it's not static you wouldn't be able to reference it from the static context (the inner class baz). It could be non-final though, because it's a field not a local.
The second part is the more interesting part, and is part of what people are talking about when they say that Java doesn't have closures: you can't modify closed over local (stack allocated) variables. However you can call methods that modify or otherwise modify heap-allocated objects, for instance if bar was an array you could modify it's contents, or if it was a Vector you could call addElement() or whatever.
In the GP's case, bar is a member field, not a local, so I don't think it needs to be final, and a quick test checks out. But if those were variables local to a method and you referenced them from an anonymous inner class, they would have to be final.
See: http://c2.com/ppr/wiki/JavaIdioms/ClosuresThatWorkAroundFinalLimitation.html http://c2.com/ppr/wiki/JavaIdioms/ClosuresThatWorkAroundFina...
If I recall correctly, from digging into the famous Guy Steele quote "we were after the C++ programmers. We managed to drag a lot of them about halfway to Lisp." I think this decision was made at the time because programmers didn't like the idea of heap-allocated local primitives. I could be totally off base here though. That wiki page mentions something about preserving the threading model, which sounds reasonable, but I don't know enough about Java's history to be totally clear on the motivation.
edited because I'm a pedant.
and the relevant message from Guy Steele: http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg04030.html http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/m... (that whole thread is fascinating, massive respect for GLS as if I didn't already, and helped quell some of my hipster Java hatred.)
- colanderman 15y agoGlad you know more about Java than I do :) I never knew about the restriction on mutating local variables in the closure. It's strange to think about that coming from the FP world where all mutable values are references to cells that (conceptually) live on the heap.