Java 8 中 Default 或 Defender 方法的用途 [英] Purpose of Default or Defender methods in Java 8

查看:17
本文介绍了Java 8 中 Default 或 Defender 方法的用途的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 8 包含一个名为 Defender 方法 的新功能,它允许创建接口中的默认方法实现.

Java 8 has included a new feature called Defender methods which allows creation of default method implementation in interface.

首先,对于所有使用 Java 的精简程序员来说,这是一个巨大的范式转变.我观看了 Brian Goetz 提供的 JavaOne 13 演示,他在那里讨论了集合库中新的 stream()parallelStream() 实现.

Now first of all this is a huge paradigm shift for all condensed programmers in Java. I viewed a JavaOne 13 presentation given by Brian Goetz where he was discussing about the new stream() and parallelStream() implementations in Collections library.

对于在Collection 接口中添加新方法,他们不可能在不破坏以前版本的情况下添加新方法.所以他说为了迎合这一点,添加了默认方法的新功能.

For adding new methods in Collection interface, they could not have just added a new method without breaking the previous versions. So he told that for catering this a new feature of Default methods was added.

public interface SimpleInterface {
  public void doSomeWork();
   
  //A default method in the interface created using "default" keyword
  default public void doSomeOtherWork(){
    System.out.println("DoSomeOtherWork implementation in the interface");
  }
}

现在我的问题基本上是默认方法只是在需要向接口添加新方法而不破坏客户端代码时有用吗?或者它还有其他用途吗?

Now my question is basically that are default methods just helpful when needed to add new methods to interface without breaking client code? Or are there some other uses to it too?

推荐答案

除了在未来版本中可以向接口添加方法之外,还有一个重要的点是允许 interface 保持一个函数式接口,即使它有多个方法.

Besides having the possibility of adding methods to the interface in future versions, there is the important point of allowing an interface to stay a functional interface even if it has more than one method.

函数式接口只有一个非默认抽象方法,可以通过 lambda 表达式实现.一个例子是Predicate 接口 它只有一个抽象方法 (test),同时提供用于否定 Predicate 或将其与另一个 Predicate 结合的默认方法.如果没有默认方法,这些方法必须在另一个实用程序类中提供,例如 Java 8 之前的 Collections 类(因为您不想放弃这种 接口的 lambda 实现的可能性).

A functional interface has only one non-default abstract method which can be implemented via a lambda expression. One example is the Predicate interface which has only one abstract method (test) while providing default methods for negating a Predicate or combining it with another Predicate. Without default methods these methods had to be provided in another utility class like the pre-Java 8 Collections class (as you don’t want to give up the possibility of lambda implementations for such an interface).

这篇关于Java 8 中 Default 或 Defender 方法的用途的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆