Wednesday, June 24, 2009

Why local classes access only final variables?

Local classes in java are of big help and a nice utility to work with making your code more encapsulated and arranged. Anonymous local inner classes is a flavour that most of us use pretty often. Now there is a strong mandate that runs with this concept, they can use only final variables of the method in which they are declared. Now why 'final', and why not non-final variables?

The reason gets clear when we delve a bit deeper and find out how local classes works.

An anonymous local class can use local variables because the compiler automatically gives the class a private instance field to hold a copy of each local variable the class uses. The compiler also adds hidden parameters to each constructor to initialize these automatically created private fields. Thus, a local class does not actually access local variables, but merely its own private copies of them. The only way this can work correctly is if the local variables are declared final, so that they are guaranteed not to change. With this guarantee in place, the local class is assured that its internal copies of the variables accurately reflect the actual local variables.