如何在Java中初始化匿名内部类 [英] How to initialize anonymous inner class in Java
问题描述
有没有办法在Java中初始化匿名内部类?
Is there any way to initialize anonymous inner class in Java?
例如:
new AbstractAction() {
actionPerformed(ActionEvent event) {
...
}
}
有没有办法在类声明中的某处使用putValue方法?
Is there any way to use for example putValue method somewhere in the class declaration?
推荐答案
使用初始化程序块:
new AbstractAction() {
{
// do stuff here
}
public void actionPerformed(ActionEvent event) {
...
}
}
初始化实例成员
Initializing Instance Members
通常情况下,你会把代码放到
初始化一个
构造函数中的实例变量。使用构造函数到
初始化实例变量有两个
替代方法:
初始化块和最终方法。
初始化程序块例如
变量看起来就像静态
初始化程序块一样,但没有
static关键字:
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
}
Java编译器将初始化程序
块复制到每个构造函数中。
因此,这种方法可以用
来共享
多个构造函数之间的代码块。
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中初始化匿名内部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!