Why Java inner classes require “final” outer instance variables? [duplicate]

Well first, let’s all relax, and please put that gun down.

OK. Now the reason the language insists on that is that it cheats in order to provide your inner class functions access to the local variables they crave. The runtime makes a copy of the local execution context (and etc. as appropriate), and thus it insists that you make everything final so it can keep things honest.

If it didn’t do that, then code that changed the value of a local variable after your object was constructed but before the inner class function runs might be confusing and weird.

This is the essence of a lot of the brouhaha around Java and “closures”.


Note: the opening paragraph was a joke in reference to some all-caps text in the original composition of the OP.

Leave a Comment