java 默认调用super,为什么我们需要super关键字来调用默认接口方法?

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();

}

解决方案

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.

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)

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值