在 Java 中显式调用默认方法 [英] Explicitly calling a default method in Java

查看:32
本文介绍了在 Java 中显式调用默认方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 8 引入了默认方法提供无需修改现有实现即可扩展接口的能力.

Java 8 introduces default methods to provide the ability to extend interfaces without the need to modify existing implementations.

我想知道当某个方法被覆盖或由于不同接口中的默认实现冲突而无法使用时,是否可以显式调用该方法的默认实现.

I wonder if it's possible to explicitly invoke the default implementation of a method when that method has been overridden or is not available because of conflicting default implementations in different interfaces.

interface A {
    default void foo() {
        System.out.println("A.foo");
    }
}

class B implements A {
    @Override
    public void foo() {
        System.out.println("B.foo");
    }
    public void afoo() {
        // how to invoke A.foo() here?
    }
}

考虑到上面的代码,你会如何从类 B 的方法中调用 A.foo() ?

Considering the code above, how would you call A.foo() from a method of class B?

推荐答案

根据 这篇文章你在接口A中使用

A.super.foo();

这可以如下使用(假设接口 AC 都有默认方法 foo())

This could be used as follows (assuming interfaces A and C both have default methods foo())

public class ChildClass implements A, C {
    @Override    
    public void foo() {
       //you could completely override the default implementations
       doSomethingElse();
       //or manage conflicts between the same method foo() in both A and C
       A.super.foo();
    }
    public void bah() {
       A.super.foo(); //original foo() from A accessed
       C.super.foo(); //original foo() from C accessed
    }
}

AC 都可以有 .foo() 方法,可以选择具体的默认实现,也可以使用一个(或两者)作为新的 foo() 方法的一部分.您还可以使用相同的语法来访问实现类中其他方法中的默认版本.

A and C can both have .foo() methods and the specific default implementation can be chosen or you can use one (or both) as part of your new foo() method. You can also use the same syntax to access the default versions in other methods in your implementing class.

方法调用语法的正式描述可以在JLS 第 15 章.

Formal description of the method invocation syntax can be found in the chapter 15 of the JLS.

这篇关于在 Java 中显式调用默认方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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