[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: bindings and assignments (was: Re: continuations)

> Out of curiosity, does anyone know why Java only allows final variables
> to be referenced from within anonymous classes?

The reason is historical.  Inner classes were added to Java as part
of the 1.1 specification and they didn't want to change the VM spec
(just the language spec) so the implementation of inner classes is a
rather ugly hack.  An anonymous inner class is compiled into a
normal class (with a munged name) and any local variables/parameters
that are used in the inner class definition are passed as arguments
to the constructor.  You are forced to declare them final since the
inner class just gets a copy (otherwise the two copies would get out
of sync).  Instance fields that are referenced by the inner class
get auto-generated set & get methods that the inner class uses so
they don't have to be final.

So, yeah, it's an ugly hack to get around the lack of closures at
the VM level.  It accomplished the goal, however: no changes to the
VM were required.  Java in a Nutshell (the only Java book I ever
used) has a pretty good description of it as I recall.

- Russ