在Java中,如果我们重载接口的默认方法会发生什么?


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

从Java 8开始,接口中引入了静态方法和默认方法。

默认方法 - 与其他抽象方法不同,这些方法可以有默认实现。如果接口中存在默认方法,则不需要在已实现此接口的类中重写(提供主体)它。

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

示例

 在线演示

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

输出

Default implementation of the display method

重写默认方法

不需要重写接口的默认方法,但是您仍然可以像重写超类的普通方法一样重写它们。但是,请确保在重写之前删除default关键字。

示例

 在线演示

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

输出

Hello welcome to Tutorialspoint

更新于:2019年9月10日

1K+ 阅读量

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.