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();      

   }

}

输出结果
This is the implementation of the demo method

This is a default method

以上是 Java中默认方法的用途是什么? 的全部内容, 来源链接: utcz.com/z/342680.html

回到顶部