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

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

问题描述

我想知道什么时候应该使用接口.

让我们思考以下问题:

公共抽象类 Vehicle {抽象浮点 getSpeed();}

和:

公共接口 IVehicle {浮动 getSpeed();}

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

使用接口的原因是什么?

谢谢!

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

解决方案

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

<块引用>

因为它们仅用作继承层次结构中的超类,我们称它们为抽象超类.这些类不能用于实例化对象,因为抽象类不完整.子类必须声明缺失的部分"成为具体"类,您可以从中实例化对象.否则,这些子类也一样,将是抽象的.

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

<块引用>

抽象类的目的是提供一个合适的超类其他类可以从中继承并因此共享一个共同的设计.

相对于接口:

<块引用>

接口描述一组可以在对象,但 不提供所有的具体实现方法...一旦一个类实现了一个接口,该类的所有对象都有与接口类型的 is-a 关系,以及 的所有对象类保证提供所描述的功能接口.该类的所有子类也是如此.

因此,为了回答您的问题我想知道什么时候应该使用接口",我认为您应该在需要完整实现时使用接口,而在需要部分设计时使用抽象类(为了可重用性)

I was wondering when I should use interfaces.

Lets think about the following:

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

and :

public interface IVehicle {
  float getSpeed();
}

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?

Thanks!

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

解决方案

From Java How to Program about abstract classes:

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.

As opposed to an 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.

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天全站免登陆