为什么我们需要super关键字来调用默认接口方法? [英] Why do we need super keyword to call default interface methods?

查看:916
本文介绍了为什么我们需要super关键字来调用默认接口方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,当我有一个实现两个具有相同默认方法签名的接口的类时,它要求我覆盖它。但是在overriden方法中为什么我必须使用super keyWord来调用默认方法。

In the below code when I am having a class implementing two interfaces with same default method signature it ask me to override it. but in the overriden method why I have to use super keyWord to call the default method.

package practice;



interface interA{

public default void AImp(){
    System.out.println("Calling Aimp from interA");
}
}


interface interB{

public default void AImp(){
    System.out.println("Calling Aimp from interB");
}
}

public class Practice implements interA,interB {

public static void main(String[] args) {


Practice inter = new Practice();

    inter.AImp();

}

@Override
public void AImp() {

    interA.super.AImp();
}
}

我可以使用以下代码执行相同的操作:

I can do the same b using below code:

@Override
public void AImp() {
    interA inter = new Practice();
    inter.AImp();
}


推荐答案

练习类实现2个接口。
即InterA和InterB。
使用的习语指定了你想要调用的两种默认方法中的哪一种。
这是因为这两种方法具有相同的签名。

Practice class implements 2 interfaces. Namely InterA and InterB. The idiom used specifies which one of the 2 default methods you wish to call. This is because the 2 methods have the same signature.

但是当您在Practice类上覆盖这样的签名时:

However when you override the signature on the Practice class like that:

package practice;

interface InterA {

    public default void AImp() {
        System.out.println("Calling Aimp from interA");
    }
}

interface InterB {

    public default void AImp() {
        System.out.println("Calling Aimp from interB");
    }
}

public class Practice implements InterA, InterB {

    public static void main(String[] args) {

        Practice inter = new Practice();

        inter.AImp();

    }

//    @Override
//    public void AImp() {
//
//        interA.super.AImp();
//    }
    @Override
    public void AImp() {
        InterA inter = new Practice();
        inter.AImp();
    }
}

您没有得到相同的结果。
你得到:

You do not get the same result. You get:

Exception in thread "main" java.lang.StackOverflowError
at practice.Practice.AImp(Practice.java:35)
at practice.Practice.AImp(Practice.java:35)
at practice.Practice.AImp(Practice.java:35)
at practice.Practice.AImp(Practice.java:35)
at practice.Practice.AImp(Practice.java:35)
at practice.Practice.AImp(Practice.java:35)
at practice.Practice.AImp(Practice.java:35)

通过InterA接口引用Practice实例,强制使用已实现的接口,它将再次实例化练习并调用AImp。这将以递归方式重复,直到抛出java.lang.StackOverflowError。

You reference an instance of Practice through the InterA interface, that forces the use of the implemented interface,which will instantiate again Practice and call AImp . This will recursively be repeated until a java.lang.StackOverflowError is thrown.

这篇关于为什么我们需要super关键字来调用默认接口方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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