Java 8默认方法与抽象类中的非抽象方法 [英] Java 8 default methods vs. non-abstract methods in abstract classes

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

问题描述

Java 8接口默认方法与抽象类中的非抽象方法
- 两者之间是否有任何差异(除了iface的差异 - 类,可见性等)。

Java 8 interface default methods vs. non-abstract methods in abstract classes - are there any differences between the two (besides the differences of iface - class, visibility etc.)

这不是Java中的默认方法,这意味着它反对Java多年来所宣传的本质吗?!

Isn't a default method a step back in Java, meaning it's against the essence that Java has advertised for years?!

推荐答案

抽象类中的非抽象方法将被调用,如果它被覆盖,则它的具体子类调用super()。所以有多种可能性。如果不覆盖方法,则将执行超类方法。如果我们在具体的子类方法中使用super(),那么将执行带有超类方法的重写方法。

non-abstract methods in abstract classes will be called when it's concrete subclass calls super() if it is overridden. So there are multiple possibilities. If method is not overridden then the super class method will be executed. if we use super() in the concrete subclass method then the overridden method with the super class method will be executed.

Java 8接口默认方法完全不同。它为开发人员提供了在实现类中实现该方法的选择。如果函数未实现那么将执行默认方法。

Where as Java 8 interface default methods are completely different. It provided a choice to the developers to implement the method in the implementing class or not. If the function is not implemented then and only then the default method will be executed.

可能的用例:

JDK库中这个新特性最重要的用例是可以在不破坏现有实现的情况下扩展现有接口:向接口添加新的抽象方法将需要所有实现类来实现新的方法。(来源

The most important use case for this new feature in the JDK libraries is the possibility to extend existing interfaces without breaking existing implementers: adding a new abstract method to an interface would require all implementing classes to implement that new method.(Source)

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

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