gpt4 book ai didi

java - Java中如何初始化匿名内部类

转载 作者:搜寻专家 更新时间:2023-10-30 19:48:18 25 4
gpt4 key购买 nike

有什么方法可以在 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/

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