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

查看:24
本文介绍了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在 Java 8 中将有诸如 forEach() 之类的方法,它们与 lambdas 结合使用.简单地将这些方法添加到预先存在的 Collection 接口是不可行的,因为它会破坏向后兼容性.我在 Java 7 中编写的实现 Collection 的类将不再编译,因为它缺少这些方法.因此,这些方法是通过默认"实现引入的.如果您了解 Scala,就会发现 Java interfaces 越来越像 Scala traits.

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天全站免登陆