默认方法在Java中的用途是什么?

默认方法在Java中的用途是什么?

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

  • 它是方法原型的规范。每当您需要指导程序员或者制定一个类型的方法和字段应该如何的契约时,您可以定义一个接口。
  • 如果您希望您的类遵循某个规范,您需要实现所需的接口,并为该接口中的所有抽象方法提供具体实现。
  • 如果您没有提供接口中所有抽象方法的实现,会生成一个编译时错误。

如果接口中添加了新的方法会怎么样?

假设我们正在使用某个接口,并且在该接口中实现了所有的抽象方法,然后后来添加了新的方法。那么,除非您在每个类中实现新添加的方法,否则使用该接口的所有类都将无法工作。

为了解决这个问题,Java8引入了默认方法。

默认方法

默认方法也被称为防御方法或虚拟扩展方法。您可以使用default关键字定义一个默认方法,如下所示:

default void display() { System.out.println("This is a default method"); }登录后复制

以下Java示例演示了在Java中使用默认方法的用法。

示例

在线演示

interface sampleInterface{ public void demo(); default void display() { System.out.println("This is a default method"); } } public class DefaultMethodExample implements sampleInterface{ public void demo() { System.out.println("This is the implementation of the demo method"); } public static void main(String args[]) { DefaultMethodExample obj = new DefaultMethodExample(); obj.demo(); obj.display(); } }登录后复制