Java 8允许在称为default methods的接口中默认实现方法。
我在什么时候使用那种接口默认方法,而不是抽象类(带有抽象方法)之间感到困惑。
那么什么时候应该使用默认方法的接口,什么时候应该使用抽象类(带有抽象方法)?抽象类在这种情况下仍然有用吗?
Java 8允许在称为default methods的接口中默认实现方法。
我在什么时候使用那种接口默认方法,而不是抽象类(带有抽象方法)之间感到困惑。
那么什么时候应该使用默认方法的接口,什么时候应该使用抽象类(带有抽象方法)?抽象类在这种情况下仍然有用吗?
当前回答
关于你对…
那么什么时候应该使用默认方法的接口,什么时候应该使用抽象类?抽象类在这种情况下仍然有用吗?
Java文档提供了完美的答案。
抽象类与接口的比较:
Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation. However, with abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods. With interfaces, all fields are automatically public, static, and final, and all methods that you declare or define (as default methods) are public. In addition, you can extend only one class, whether or not it is abstract, whereas you can implement any number of interfaces.
它们各自的用例已经在下面的SE帖子中解释了:
接口和抽象类的区别是什么?
抽象类在这种情况下仍然有用吗?
是的。它们仍然有用。它们可以包含非静态的、非最终的方法和属性(受保护,除了公共之外还有私有),这即使是Java-8接口也不可能实现。
其他回答
如本文所述,
Java 8中的抽象类与接口
After introducing Default Method, it seems that interfaces and abstract classes are same. However, they are still different concept in Java 8. Abstract class can define constructor. They are more structured and can have a state associated with them. While in contrast, default method can be implemented only in the terms of invoking other interface methods, with no reference to a particular implementation's state. Hence, both use for different purposes and choosing between two really depends on the scenario context.
Java Interface中的默认方法将更多地用于提供函数的虚拟实现,从而使该接口的任何实现类不必声明所有抽象方法,即使它们只想处理一个抽象方法。 因此,接口中的默认方法在某种程度上更像是适配器类概念的替代品。
然而,抽象类中的方法应该给出一个有意义的实现,只有在需要覆盖一个通用功能时,任何子类才应该覆盖它。
Java接口中的默认方法支持接口演进。
对于现有的接口,如果希望在不破坏接口旧版本的二进制兼容性的情况下向其添加方法,有两个选择:添加默认方法或静态方法。实际上,添加到接口中的任何抽象方法都必须由实现该接口的类或接口来实现。
静态方法对于类来说是唯一的。默认方法对于类的实例是唯一的。
如果向现有接口添加默认方法,实现该接口的类和接口不需要实现它。他们可以
实现默认方法,它将覆盖已实现接口中的实现。 重新声明方法(没有实现),使其抽象。 什么都不做(然后简单地继承实现接口的默认方法)。
更多关于这个话题的信息请点击这里。
抽象类比默认方法实现(如私有状态)要多得多,但从Java 8开始,无论何时您可以选择其中任何一种,都应该选择防御器(也就是私有状态)。默认)方法。
默认方法的限制是它只能通过调用其他接口方法来实现,而不能引用特定实现的状态。所以主要的用例是高级和方便的方法。
这个新特性的好处在于,以前您必须使用抽象类来实现方便的方法,从而将实现者限制为单一继承,现在您可以拥有一个真正干净的设计,只需要接口,并且强制程序员进行最少的实现工作。
向Java 8引入默认方法的最初动机是希望在不破坏任何现有实现的情况下,使用面向lambda的方法扩展集合框架接口。虽然这与公共图书馆的作者更相关,但您可能会发现相同的特性在您的项目中也很有用。您有一个集中的地方可以添加新的便利,而不必依赖于类型层次结构的其余部分。
什么时候应该使用缺省方法的接口,什么时候应该使用 抽象类被使用?
向后兼容性: 想象一下,你的接口是由数百个类实现的,修改这个接口将迫使所有用户实现新添加的方法,即使它对于实现你的接口的许多其他类来说可能不是必需的。另外,它允许你的接口成为一个功能接口
事实与限制:
1-只能在接口中声明,而不能在类或 抽象类。
2 .必须提供一个主体
它不像接口中使用的其他常规方法那样被认为是抽象的。