Possible Duplicate:
Cannot refer to a non-final variable inside an inner class defined in a different method
Why are only final variables accessible in anonymous class?
Looked over in SO and google looking for an answer to this question but could not find any.
I have the following code:
MyClass variable = new MyClass();
Button b = new Button();
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
System.out.println("You clicked the button");
variable.doSomething();
}
});
The compiler returns this:
local variable variable is accessed from within inner class; needs to
be declared final
What are the technical reasons why variable must be final?
It is because you are using anonymous inner class.
What happens is that compiler creates class for you. It calls it as your outer class and adds
$and number, e.g.$,$2etc.The class has reference to outer class initialized automatically, so its instance can use methods and fields of outer class.
But your class is anonymous. It kind of defined inside method and can use its internal variables defined before this anonymous class. The question is “how can it do it?” Really, you cannot refer to “instance of running method” to access its variables. The answer is that all method variables referenced from anonymous inner class are copied to the anonymous inner class . Therefore the variables are required to be final: otherwise somebody can change their values from the outer class and the changes will not be visible into the inner class.