Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.3k views
in Technique[技术] by (71.8m points)

如何调用接口中的默认方法?

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呢? 为什么这么写?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...