我们可以覆盖Java中的默认方法吗?

Java中的接口与类相似,但是它仅包含final和static的抽象方法和字段。

由于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 MyInterface{  
   public static int num = 100;
   public default void display() {
      System.out.println("display method of MyInterface");
   }
}
public class InterfaceExample implements MyInterface{
   public void display() {
      System.out.println("display method of class");
   }
   public static void main(String args[]) {
      InterfaceExample obj = new InterfaceExample();
      obj.display();
   }
}
输出结果
display method of class