是否必须重写Java中接口的默认方法?

从Java8开始,默认方法在接口中引入。与其他抽象方法不同,这些方法可以具有默认实现。如果您在接口中具有默认方法,则不必在已经实现此接口的类中重写(提供正文)。

简而言之,您可以使用实现类的对象来访问接口的默认方法。

示例

interface MyInterface{
   public static int num = 100;
   public default void display() {
      System.out.println("display method of MyInterface");
   }
}
public class InterfaceExample implements MyInterface{
   public static void main(String args[]) {
      InterfaceExample obj = new InterfaceExample();
     obj.display(); 
   }
}

输出结果

display method of MyInterface

但是,当您的类实现两个接口,并且它们都具有名称和原型相同的方法时。您必须重写此方法,否则会生成编译时错误。

示例

interface MyInterface1{
   public static int num = 100;
   public default void display() {
      System.out.println("display method of MyInterface1");
   }
}
interface MyInterface2{
   public static int num = 1000;
   public default void display() {
      System.out.println("display method of MyInterface2");
   }
}
public class InterfaceExample implements MyInterface1, MyInterface2{
   public static void main(String args[]) {
      InterfaceExample obj = new InterfaceExample();
      //obj.display(); 
   }
}

编译时错误

InterfaceExample.java:14: error: class InterfaceExample inherits unrelated defaults for display() from types MyInterface1 and MyInterface2
public class InterfaceExample implements MyInterface1, MyInterface2{
^
1 error

为了解决这个问题,您需要重写display()实现类中的一个(或两个)方法-

示例

interface MyInterface1{
   public static int num = 100;
   public default void display() {
      System.out.println("display method of MyInterface1");
   }
}
interface MyInterface2{
   public static int num = 1000;
   public default void display() {
      System.out.println("display method of MyInterface2");
   }
}
public class InterfaceExample implements MyInterface1, MyInterface2{
   public void display() {
      MyInterface1.super.display();
      //或
      MyInterface2.super.display();
   }
   public static void main(String args[]) {
      InterfaceExample obj = new InterfaceExample();
     obj.display(); 
   }
}

输出结果

display method of MyInterface1
display method of MyInterface2