Java 8:虚拟扩展方法与抽象类 [英] Java 8: virtual extension methods vs abstract class

查看:539
本文介绍了Java 8:虚拟扩展方法与抽象类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究Java 8接口中的新虚拟扩展方法:

I'm looking at the new virtual extension methods in Java 8 interfaces:

public interface MyInterface {
   default String myMethod() { 
      return "myImplementation"; 
   }
}

我的目的是允许接口进化时间和多重继承位,但它们看起来非常像我的抽象类。

I get their purpose in allowing an interface to evolve over time, and the multiple inheritance bit, but they look awfully like an abstract class to me.

如果你正在做新工作,抽象类优先于扩展方法提供实现到接口还是这两种方法在概念上是等价的?

If you're doing new work are abstract classes prefered over extension methods to provide implementation to an "interface" or are these two approaches conceptually equivalent?

推荐答案

此类构造的一个主要目的是保持向后兼容性。在Java语言中添加闭包是一个很大的改动,需要更新一些内容才能充分利用这一点。例如, Collection 将包含 forEach()等方法,它们与lambdas一起使用。简单地将这些方法添加到预先存在的 Collection 接口是不可行的,因为它会破坏向后兼容性。我在Java 7中编写的实现 Collection 的类将不再编译,因为它缺少这些方法。因此,这些方法是通过默认实现引入的。如果您了解Scala,您可以看到Java 接口 s变得更像Scala trait s。

One primary purpose of such constructs is to preserve backwards compatibility. The addition of closures to the Java language is quite a major alteration, and things need to be updated to fully take advantage of this. For example, Collection in Java 8 will have methods such as forEach() which work in conjunction with lambdas. Simply adding such methods to the pre-existing Collection interface would not be feasible, since it would break backwards compatibility. A class I wrote in Java 7 implementing Collection would no longer compile since it would lack these methods. Consequently, these methods are introduced with a "default" implementation. If you know Scala, you can see that Java interfaces are becoming more like Scala traits.

至于接口与抽象类,这两者在Java 8中仍然是不同的;例如,您仍然无法在界面中拥有构造函数。因此,这两种方法本身并不是概念上等同的。抽象类更结构化,可以具有与之关联的状态,而接口则不能。你应该在程序的上下文中使用更有意义的东西,就像在Java 7及以下版本中那样。

As for interfaces vs abstract classes, the two are still different in Java 8; you still can't have a constructor in an interface, for example. Hence, the two approaches are not "conceptually equivalent" per se. Abstract classes are more structured and can have a state associated with them, whereas interfaces can not. You should use whichever makes more sense in the context of your program, just like you would do in Java 7 and below.

这篇关于Java 8:虚拟扩展方法与抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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