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

查看:47
本文介绍了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天全站免登陆