<分区>
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?
在 SO 和谷歌中寻找这个问题的答案,但找不到任何答案。
我有以下代码:
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();
}
});
编译器返回:
local variable variable is accessed from within inner class; needs to be declared final
variable
必须是 final 的技术原因是什么?