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

查看:68
本文介绍了在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?
    }
}

考虑到上面的代码,你怎么称呼 A.foo()来自B类方法?

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

推荐答案

按照这篇文章您可以在界面中访问默认方法A 使用

A.super.foo();

这可以如下使用(假设接口 A C 都有默认方法 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
    }
}

A C 都可以有 .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天全站免登陆