Why do I need to declare a local variable
as final
if my Inner class
defined within the method needs to use it ?
Example :
I think this is to prevent that the programmer would make mistakes. This way, the compiler reminds the programmer that the variable will not be accessible anymore when you leave that method. This is critical with looping. Imagine this code:
public void doStuff()
{
InnerClass cls[] = new InnerClass[100];
for (int i = 0; i < 100; ++i)
{
cls[i] = new InnerClass()
{
void doIt()
{
System.out.println(i);
}
};
}
}
When the doIt()
method is called, what will be printed? i
changed while looping.
To prevent that confusion, you have to copy the variable to a local variable or create the variable final, but then you will be unable to loop.