有什么方法可以在 Java 中初始化匿名内部类?
例如:
new AbstractAction() {
actionPerformed(ActionEvent event) {
...
}
}
有什么方法可以在类声明的某处使用例如 putValue 方法吗?
最佳答案
使用初始化 block :
new AbstractAction() {
{
// do stuff here
}
public void actionPerformed(ActionEvent event) {
...
}
}
初始化实例成员
Normally, you would put code to initialize an instance variable in a constructor. There are two alternatives to using a constructor to initialize instance variables: initializer blocks and final methods. Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:
{
// whatever code is needed for initialization goes here
}
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
来源:
关于java - Java中如何初始化匿名内部类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5310403/