java - 匿名类的多重继承

标签 java multiple-inheritance anonymous-class

匿名类如何实现两个(或更多)接口(interface)?或者,它如何扩展一个类实现一个接口(interface)? 例如,我想创建一个扩展两个接口(interface)的匿名类对象:

    // Java 10 "var" is used since I don't know how to specify its type
    var lazilyInitializedFileNameSupplier = (new Supplier<String> implements AutoCloseable)() {
        private String generatedFileName;
        @Override
        public String get() { // Generate file only once
            if (generatedFileName == null) {
              generatedFileName = generateFile();
            }
            return generatedFileName;
        }
        @Override
        public void close() throws Exception { // Clean up
            if (generatedFileName != null) {
              // Delete the file if it was generated
              generatedFileName = null;
            }
        }
    };

然后我可以在 try-with-resources block 中使用它作为 AutoCloseable 作为延迟初始化的实用程序类:

        try (lazilyInitializedFileNameSupplier) {
            // Some complex logic that might or might not 
            // invoke the code that creates the file
            if (checkIfNeedToProcessFile()) {
                doSomething(lazilyInitializedFileNameSupplier.get());
            }
            if (checkIfStillNeedFile()) {
                doSomethingElse(lazilyInitializedFileNameSupplier.get());
            }
        } 
        // By now we are sure that even if the file was generated, it doesn't exist anymore

我不想创建一个内部类,因为我绝对确定这个类不会在任何地方使用,除了我需要在其中使用它的方法(我也可能想要使用在该方法中声明的可能是 var 类型的局部变量)。

最佳答案

匿名类必须扩展或实现某些东西,就像任何其他 Java 类一样,即使它只是 java.lang.Object

例如:

Runnable r = new Runnable() {
   public void run() { ... }
};

这里,r是一个匿名类的对象,它实现了Runnable

匿名类可以使用相同的语法扩展另一个类:

SomeClass x = new SomeClass() {
   ...
};

你不能做的是实现多个接口(interface)。你需要一个命名类来做到这一点。然而,匿名内部类和命名类都不能扩展多个类。

关于java - 匿名类的多重继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5848510/

相关文章:

Java:我应该在哪里放置匿名监听器逻辑代码?

Java Rest 删除错误

java - 将 CDI/EJB 注解迁移到 Spring 注解

java - Jsoup登录爬取游戏数据

java - Hibernate:自动版本控制可空列

c++ - C++ 中的多重多态

c++ - 将接口(interface) `ISingleton` 抽象为基类

java - 在无限循环中使用匿名类与嵌套类(Java)

c++ - 菱形继承(钻石问题) (C++)

java - java中匿名内部类成员不可访问