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

java 8object oriented programmingprogramming更新于 2025/9/19 16:12:17

从 Java 8 开始,接口中引入了默认方法。与其他抽象方法不同,这些方法可以拥有默认实现。如果接口中有默认方法,则无需在已实现此接口的类中重写(提供方法体)。

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

示例

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();
      //or,
      MyInterface2.super.display();
   }
   public static void main(String args[]) {
      InterfaceExample obj = new InterfaceExample();
      obj.display();
   }
}

输出

display method of MyInterface1
display method of MyInterface2

相关文章