I need to explain why the following code would fail to compile (in terms of scope and lifetime):
class ClassInMethod
{
public static void main(String[] args)
{
int local = 1;
class Inner
{
public void method()
{
System.out.println(local);
}
}
}
}
I think it’s because:
Any local variable used but not declared in an inner class must be declared ‘final’. Thus, in this example ‘local’ must be declared final because its scope and lifetime end within the main method (so needs to be changed to: final int local = 1;).
Any other suggestions?
The reason why you have to make the local variables
finalis that Java copies their values into the instance of the inner class. What happens behind the scenes is that the compiler generates bytecode that (roughly) corresponds to this:If
localweren’tfinal, and you could change its value between whenInneris instantiated, and whenmethod()is called, the call tomethod()would use the old value oflocal. This would likely be incorrect behaviour. The reasonfinalis mandated is to make the behaviour of inner classes more intuitive.(There are languages that don’t have this restriction, but it requires explicit support from the compiler and runtime. Java’s developers have so far not decided to dedicate their effort to implementing it.)