How to invoke an interface's default implementation of a method in an overriding implementation?

北慕城南 提交于 2019-12-05 12:59:16

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");
    }       
}

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

The output will be:

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

when you run:

new Tester().doWork();
HumanoidForm.super.reproduce();

Take a look at this: https://blog.idrsolutions.com/2015/01/java-8-default-methods-explained-5-minutes/

In particular the section where it says "If we want to specifically invoke one of the sayHi() methods in either InterfaceA or InterfaceB, we can also do as follows:"

public class MyClass implements InterfaceA, InterfaceB {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // TODO code application logic here
}

@Override
public void saySomething() {
    System.out.println("Hello World");
}

@Override
public void sayHi() {
   InterfaceA.super.sayHi();
}

}

interface InterfaceA {

public void saySomething();

default public void sayHi() {
    System.out.println("Hi from InterfaceA");
}

}

interface InterfaceB {
 default public void sayHi() {
    System.out.println("Hi from InterfaceB");
}
}

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

No, you can reuse the code. You can easily test it and you will see that the following code works:

public class Test implements HumanoidForm
{             
    public static void main(String[] args) 
    {       
        new Test().reproduce();         
    }   

    @Override
    public void reproduce(){
        HumanoidForm.super.reproduce();  //Invoking default method
        System.out.println("From implementing class");
    }       
}

interface HumanoidForm {
    default void reproduce() {
       System.out.println("From default interface");
    }
}

OUTPUT:

From default interface
From implementing class
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!