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

标签 java

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

相关文章:

java - 将字符串转换为日期 - 罗马月

javascript - Node.js 服务器限制新连接

Java 静态方法调用

java - Spring Boot @EnableScheduling 有条件地

java - 除了类和接口(interface)之外,我们还可以在java源文件中编写其他内容吗?

java - 自定义标签 'cannot be resolved to a type'

java - 将Java连接到MySQL数据库

java - 如何将 JSON 对象发布到 URL?

java - 在构建过程中集成系统测试

java - 将图像上传到 Android 中 Parse Cloud 中的 User 表