[英]Java inline interface implementation, variables and method calls
In Java, why can I do this 在Java中,为什么可以这样做
new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
screenClosed();
}
}
// ...
public void screenClosed() {
running = false;
}
but not 但不是
new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
running = false;
}
}
? ?
I'm guessing that running
is a local variable, not a field in your second example, and you have to make it a field with the screenClosed
method to make it work? 我猜在
running
是一个局部变量,而不是第二个示例中的字段,您必须使用screenClosed
方法使其成为一个字段才能使其正常工作? It's hard to tell from your code sample. 从您的代码示例很难分辨。
If so: inner classes such as local or anonymous classes require that (local) variables are marked final
(they are constants). 如果是这样:内部类(例如本地或匿名类)要求将(本地)变量标记为
final
(它们是常量)。 This is due to the way the compiler constructs the class by passing the variable as an argument to the compiler-created constructor, and then storing it as a field in the compiler-generated class. 这是由于编译器通过将变量作为参数传递给编译器创建的构造函数,然后将其作为字段存储在编译器生成的类中而构造类的方式所致。
You can get around this limitation by declaring the local variable as: 您可以通过将局部变量声明为以下方式来解决此限制:
final boolean[] running = new boolean[]{true};
and then setting running[0] = false
instead. 然后设置
running[0] = false
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.