Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

public interface MyFun {

default String getName(){
    return "哈哈哈";
}

}

public interface MyInterface {


default String getName(){
    return "呵呵呵";
}

public static void show(){
    System.out.println("接口中的静态方法");
}

}

public class SubClass implements MyFun, MyInterface{

@Override
public String getName() {
    return MyInterface.super.getName();
}

}

看到这样的代码,MyInterface.super.getName();这块不太明白,为什么要 点super才能调getName呢? 为什么这么写?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.4k views
Welcome To Ask or Share your Answers For Others

1 Answer

这里因为是实现的两个接口都有同名的default方法,所以需要指定使用哪一个接口的方法做为实现.
<interface>.super.<method> 是专门用于此场景的语法.

为什么不直接用<interface>.<method> 调用呢?
因为<interface>.<method>写法是用来调用static修饰的方法的,default方法并不是static方法,所以在此不适用.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...