java扩展方法,Java 8:虚拟扩展方法与抽象类

本文探讨了Java 8中接口引入的默认方法,它们如何促进接口演进并支持多继承,同时与抽象类进行比较。讨论了为何在保留向后兼容性的前提下,它们在实现‘接口’功能时的作用。此外,文章指出接口与抽象类的区别,如构造器限制和状态管理,并建议根据项目需求灵活选用。
摘要由CSDN通过智能技术生成

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?

解决方案

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.

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值