【问题标题】:Same named default method in multiple inheritance interfaces. Java [duplicate]多继承接口中的同名默认方法。 Java [重复]
【发布时间】:2020-01-10 16:18:40
【问题描述】:

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

【问题讨论】:

  • 你运行它时得到了什么输出?
  • 我得到了 "interface1" ,没有错误,但不知道为什么它是 1 ?
  • 您的代码不会为我编译。我收到预期的错误“使用参数 () 和 () 的名为 printMsg 的重复默认方法是从类型 Interface2 和 Interface1 继承的”,不过这是使用 Java 8。您使用的是什么版本的 Java?

标签: java


【解决方案1】:

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

Test.java:13:错误:Interface1 和 Interface2 类型不兼容; 接口接口 3 扩展接口 1、接口 2{} ^

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

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

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

【讨论】:

    猜你喜欢
    • 2011-08-13
    • 2019-05-08
    • 1970-01-01
    • 2010-11-09
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 2014-12-31
    • 2013-12-06
    相关资源
    最近更新 更多