我何时必须使用接口而不是抽象类? [英] When do I have to use interfaces instead of abstract classes?

查看:243
本文介绍了我何时必须使用接口而不是抽象类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道何时应该使用接口。

I was wondering when I should use interfaces.

让我们考虑以下事项:

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

和:

public interface IVehicle {
  float getSpeed();
}

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

I can easily implement both of them, they have the same functionality... BUT I also can add some variables to my vehicle class, which probably should be used in an vehicle (maxSpeed, carType...)

使用接口的原因是什么?

What is the reason to use interfaces?

谢谢!

编辑:我发现了一个很好的链接另一个主题: http://www.thecoldsun.com/ en / content / 01-2009 / abstract-classes-and-interfaces

I found a nice link about it in another thread: http://www.thecoldsun.com/en/content/01-2009/abstract-classes-and-interfaces

推荐答案

来自 Java如何编程关于抽象类:


因为它们仅用作继承层次结构中的超类,所以
我们将它们称为抽象超类。 这些类不能用于实例化对象的
,因为抽象类是不完整的。

子类必须声明缺失部分成为具体类,
来自你可以实例化对象。否则,这些子类,
也将是抽象的。

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.

回答你的问题使用接口的原因是什么?:

To answer your question "What is the reason to use interfaces?":


抽象类的目的是提供一个合适的超类
,其他类来自可以继承并共享一个共同的设计。

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

与界面相反:


接口描述可以在
对象上调用的一组方法,但不为所有$ b提供具体实现$ b方法 ...一旦类实现了一个接口,该类的所有对象都具有
与接口类型的关系,以及
类的所有对象保证提供
接口描述的功能。
这个类的所有子类都是如此。

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.

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

So, to answer your question "I was wondering when I should use interfaces", I think you should use interfaces when you want a full implementation and use abstract classes when you want partial pieces for your design (for reusability)

这篇关于我何时必须使用接口而不是抽象类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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