gpt4 book ai didi

java - 变量应该在监听器中是最终的

转载 作者:行者123 更新时间:2023-11-30 05:53:06 28 4
gpt4 key购买 nike

<分区>

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 的技术原因是什么?

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com