匿名类的多重继承 [英] Multiple inheritance for an anonymous class

查看:51
本文介绍了匿名类的多重继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can an anonymous class implement two (or more) interfaces? Alternatively, how can it both extend a class and implement an interface? For example, I want to create an object of anonymous class that extends two interfaces:

    // 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;
            }
        }
    };

然后,我可以将其作为 AutoCloseable 作为惰性初始化的实用程序类在try-with-resources块中使用:

Then I can use it in a try-with-resources block as AutoCloseable as lazily-initialized utility class:

        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 类型).

I don't want to create an inner class because I'm absolutely sure that this class won't be used anywhere except the method I need to use it in (and I also might want to use local variables declared in that method that might be of var type).

推荐答案

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

Anonymous classes must extend or implement something, like any other Java class, even if it's just java.lang.Object.

例如:

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

在这里, r 是实现 Runnable 的匿名类的对象.

Here, r is an object of an anonymous class which implements Runnable.

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

An anonymous class can extend another class using the same syntax:

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

您不能做的就是实现多个接口.您需要一个命名类来做到这一点.但是,匿名内部类和命名类都不能扩展多个类.

What you can't do is implement more than one interface. You need a named class to do that. Neither an anonymous inner class, nor a named class, however, can extend more than one class.

这篇关于匿名类的多重继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆