多个继承接口中具有相同名称的默认方法。爪哇

时间:2020-01-10 16:18:40

标签: java

interface1具有默认方法“ void printMsg()”

public interface Interface1 {
    default void printMsg(){
        System.out.println("interface1");
    }
}

interface2还具有默认方法“ void printMsg()”

public interface Interface2 {
    default void printMsg(){
        System.out.println("interface2");
    }
}

interface3扩展了两个接口

public interface Interface3  extends Interface1, Interface2{}

现在ClassA同时具有Interface1.printMsg()和Interface2.printMsg()

class ClassA implements Interface3{
    ClassA(){}
}

下面的代码输出什么,为什么?

new ClassA().printMsg();

1 个答案:

答案 0 :(得分:0)

它不会编译。这是我得到的输出:

Test.java:13:错误:Interface1和Interface2类型不兼容; 接口Interface3扩展了Interface1,Interface2 {} ^

interface Interface3从类型Interface1和Interface2继承printMsg()的不相关默认值

Test.java:15:错误:Interface1和Interface2类型不兼容; ClassA类实现Interface3 { ^

ClassA类从类型Interface1和Interface2继承printMsg()的不相关默认值