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

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

问题描述

Java 8包含一项名为后卫方法的新功能,可以创建接口中的默认方法实现。

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

现在首先,对于Java中所有精简程序员来说,这是一个巨大的范例转换。我查看了Brain Goetz给出的JavaOne 13演示文稿,他在讨论新的 stream() parallelStream() Collections库中的实现。

Now first of all this is a huge paradigm shift for all condensed programmers in Java. I viewed a JavaOne 13 presentation given by Brain 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?

推荐答案

除了可以在将来的版本中添加方法到界面外是允许接口保留功能接口的重要一点,即使它有多种方法。

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 ),同时提供否定谓词的默认方法或者将它与另一个谓词组合。如果没有默认方法,这些方法必须在另一个实用程序类中提供,例如pre-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天全站免登陆