本文介绍了为什么在Java 8中向接口添加默认方法是一个不错的设计选择,还有哪些替代方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在学习Java,所以很难访问可能的替代方案以及这种设计决策的影响.

I am just learning Java, so it is hard for me to access the possible alternatives, and the impact of such a design decision.

Java 8向接口添加了默认方法功能,该功能允许接口实现.这允许使用新方法扩展现有接口,而不会破坏客户端,并以向后兼容的方式随着时间的推移不断发展接口.但是,在给定默认实现的情况下,此类扩展在一定程度上受到限制,并且很可能使用接口的现有接口方法或库方法来实现.所以我的问题是

Java 8 adds the default methods feature to interfaces, which allows interfaces to have an implementation.This allows to extend the existing interfaces with new methods, without breaking the clients, evolving the interface over time in a backward-compatible way.However, given default implementation, such extensions are somewhat limited, and are likely to be implemented using existing interface methods of the interface or library methods.So my question is

  • 为什么要引入此语言功能?
  • 它支持哪些主要新功能? (例如Splititerators)
  • 还有哪些其他替代方法可以支持这些语言功能?例如,为什么不创建一个扩展Iterable的新接口SplitIterable?
  • 实施这些替代方案(接口的精加工?)会产生什么影响
  • 如果可以将其实现为其他方法的组合,我是否应该在接口的第一版中为该方法提供默认实现?

推荐答案

主要是为了使您可以在不破坏每个人的代码的情况下向已使用的现有接口中添加方法,还可以在实现同一接口的类之间水平"共享方法实现(与通过继承进行垂直"共享相反) ).

It was added primarily to let you add methods to existing interfaces that are already in use without breaking everyone's code, but also to share method implementations "horizontally" across classes implementing the same interface (as opposed to "vertical" sharing through inheritance).

java.util.Collection<T>.stream()

您可以选择全新的界面,并继续使用关联的静态帮助程序类(例如Collection<T>接口及其Collections助手类).这并不可怕-实际上,有人可能会说默认方法纯粹是静态方法之上的语法糖.但是,默认方法通常可提供更好的可读性.

You could opt for entirely new interfaces, and continue with the associated static helper class (e.g. Collection<T> interface and its Collections helper class). This wouldn't be terrible - in fact, one could argue that default methods are purely a syntactic sugar on top of static methods. However, default methods generally provide for better readability.

您最终会获得一个不太统一的库和一个可读性较低的语言,但这并不是世界末日. Joachim Sauer 指出的一个更大的问题是,接口实现将无法从静态助手类.那会失去灵活性.

You would end up with a less consistent library, and a less readable language, but it wouldn't be the end of the world. A bigger concern, as pointed out by Joachim Sauer, is that interface implementations would have no way to override implementation from the static helper class. That would take away flexibility.

仅当您需要水平"共享实施时,才应该这样做.如果某个方法提供了实现的基本行为,则不要为其提供默认值.

You should do it only if you need to share implementation "horizontally". If a method provides essential behavior of the implementation, do not provide a default for it.

这将过于简化,因为默认方法仍然是虚拟的.感谢 Brian Goetz 的评论.

This would be an oversimplification, because default methods remain virtual. Thanks Brian Goetz for the comment.

这篇关于为什么在Java 8中向接口添加默认方法是一个不错的设计选择,还有哪些替代方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 20:39