java - 什么时候必须使用接口(interface)而不是抽象类?

标签 java oop inheritance interface abstract-class

我想知道什么时候应该使用接口(interface)。

让我们思考以下问题:

public abstract class Vehicle {
   abstract float getSpeed();
}

和:

public interface IVehicle {
  float getSpeed();
}

我可以很容易地实现它们,它们具有相同的功能...但我也可以向我的车辆类添加一些变量,这些变量可能应该在车辆中使用(maxSpeed、carType...)

使用接口(interface)的原因是什么?

谢谢!

编辑:我在另一个线程中找到了一个很好的链接:http://www.thecoldsun.com/en/content/01-2009/abstract-classes-and-interfaces

最佳答案

来自 Java How to Program关于抽象类:

Because they’re used only as superclasses in inheritance hierarchies, we refer to them as abstract superclasses. These classes cannot be used to instantiate objects, because abstract classes are incomplete. Subclasses must declare the “missing pieces” to become “concrete” classes, from which you can instantiate objects. Otherwise, these subclasses, too, will be abstract.

回答您的问题“使用接口(interface)的原因是什么?”:

An abstract class’s purpose is to provide an appropriate superclass from which other classes can inherit and thus share a common design.

相对于接口(interface):

An interface describes a set of methods that can be called on an object, but does not provide concrete implementations for all the methods... Once a class implements an interface, all objects of that class have an is-a relationship with the interface type, and all objects of the class are guaranteed to provide the functionality described by the interface. This is true of all subclasses of that class as well.

所以,为了回答你的问题“我想知道什么时候应该使用接口(interface)”,我认为当你想要一个完整的实现时你应该使用接口(interface),当你想要设计的部分部分时使用抽象类(为了可重用性)

关于java - 什么时候必须使用接口(interface)而不是抽象类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16781329/

相关文章:

未调用 Java Rest Put 方法 (Jersey/JAX)

java - SWT 分区表和滚动

c# - 创建一个接受多种类型对象的 C# 方法?

Java:使用子级的成员变量调用父级的方法

python - 在 Python 中使用 super() 进行 DRY

c++ - 在不知道派生类的情况下从父类调用派生类函数

java - 如何使用sendRedirect或session或forward仅刷新我的网页一次?

java - 如何在更改 JLabel 大小时动态缩放图像

python - 在Python中访问类中的类成员的最佳方法

C# : dynamic polymorphism with non polymorphic classes