如何在覆盖实现中调用接口的默认方法实现? [英] How to invoke an interface's default implementation of a method in an overriding implementation?

查看:563
本文介绍了如何在覆盖实现中调用接口的默认方法实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下代码:

interface HumanoidForm {
    default HumanoidForm reproduce() {
        <appropriate code for humanoid form reproduction>
    }
}

class Android extends Machine implements HumanoidForm {
    public HumanoidForm reproduce() {
        <appropriate code for android reproduction> // how to use HumanoidForm's default implementation here?
    }
}

现在假设适用于Android再现的代码是最好的通过使用用于仿人形式再现的适当代码作为子程序来描述。如何从适用于Android复制的代码中访问适合人形的代码?我可以想到三种方法,但它们都不起作用:

Now suppose "appropriate code for android reproduction" is best described by using "appropriate code for humanoid form reproduction" as a sub-routine. How can I access "appropriate code for humanoid form" from within "appropriate code for android reproduction"? I can think of three ways, but none of them works:


  • 只需调用reproduce()即可调用覆盖的实现。
  • 写((HumanoidForm)this).reproduce()仍然调用重写的实现。
  • 通过重写方法模仿超类中方法实现的重用,可以考虑编写super.reproduce()。然而,这指的是机器的再现实现,甚至可能不存在。
  • Simply invoking reproduce() invokes the overriding implementation.
  • Writing ((HumanoidForm) this).reproduce() still invokes the overriding implementation.
  • Mimicking the re-use of implementations of methods in super classes by overriding methods, one may think of writing super.reproduce(). However, that refers to Machine's implementation of reproduce, which may not even exist.

所以似乎没有办法重新使用默认方法中的代码来覆盖。那是真的吗?

So it seems there is no way to re-use the code in the default method for overriding. Is that really so?

推荐答案

实际上,您可以自由选择现有的实施方式。让我给你一个比你更复杂的场景。更糟糕的是,所有 A B & C 具有相同的方法签名。

Actually, you can choose freely the existing implementation. Let me give you a scenario slightly more complicated than yours. To make things worse, all A,B & C has the same method signature.

interface A {
    default void doWork() {
       System.out.println("Default implementation From A");
    }
}

interface B{
    default void doWork() {
      System.out.println("Default implementation From B");  
    }   
}

class C{
    void doWork(){
        System.out.println("Default implementation From C");
    }       
}

现在,我为C创建一个实现A的子类&安培; B:

Now, I create a subclass to C which implements A & B:

class Tester extends C implements A, B
{
    @Override public void doWork(){
        A.super.doWork();  //Invoke A's implementation
        B.super.doWork();  //Invoke B's implementation
        super.doWork();    //Invoke C's implementation
    }
}






输出将是:

Default implementation From A
Default implementation From B
Default implementation From C

运行时

new Tester().doWork();

这篇关于如何在覆盖实现中调用接口的默认方法实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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