这可能是一个通用的OOP问题。我想在接口和抽象类的使用基础上做一个通用的比较。

什么时候需要使用接口,什么时候需要使用抽象类?


当前回答

答案因语言而异。例如,在Java中,一个类可以实现(继承)多个接口,但只能继承一个抽象类。所以接口给了你更多的灵活性。但在c++中却不是这样。

其他回答

什么时候做什么是一件非常简单的事情,如果你有清晰的概念在你的脑海里。

抽象类可以是派生类,而接口可以是实现类。这两者之间有一些区别。当派生抽象类时,派生类和基类之间的关系是“is a”关系。例如,狗是动物,羊是动物,这意味着派生类从基类继承了一些属性。

而对于接口的实现,关系是“可以是”。例:狗可以是间谍犬。狗可以是马戏团的狗。狗可以是比赛犬。这意味着你要实现特定的方法来获取某些东西。

我希望我讲清楚了。

两者都是类定义的契约:

结论1:两种意图都是对象泛化

在定义抽象类时,它们也可以有默认实现。

结论2:区分存在于行为泛化设计中

在使用抽象类时,类只能从一个抽象类继承

结论3:抽象类在应用上存在局限性。它的意思是 行为概括的局限性。

最后结论-何时使用哪个:区分是在行为泛化层面

在类的行为设计中,如果功能在确定的类之间只是概念上的限制,换句话说,在确定的类之间是共享的,则使用抽象类。但如果功能比确定类更通用,或者我们可以/想要向其他类添加功能,则使用接口作为契约。

基本的经验法则是:对于“名词”使用抽象类,对于“动词”使用接口

例如:car是一个抽象类和驱动器,我们可以让它成为一个接口。

车辆包括汽车、坦克、飞机、手推车等。

抽象类Vehicle可以有子类,如car、tank、plane、cart等。

public abstract Vehicle {...}

public Car extends Vehicle {...}

public Tank extends Vehicle {...}

那么,什么是可移动的?几乎一切! 然后

石头,蛋糕,汽车,行星,星系,甚至你都是可移动的!

它们中的大多数也是可观察的!

什么是可吃的?这是一款名为《美味星球》的游戏。 然后

石头,汽车,行星,星系,甚至时间!

public interface Movable {...}
public interface Observable {...}
public interface Eatable {...}

public class Stone implements Movable, Eatable, Observable {...}

public class Time implements Eatable, Observable {...}

public class Stupidity implements Observable {...}

终于!

public class ChocolateCar extends Vehicle implements Eatable {...}

类只能继承自一个基类,因此如果您想使用抽象类为一组类提供多态性,它们必须全部继承自该类。抽象类也可以提供已经实现的成员。因此,您可以使用抽象类确保一定数量的相同功能,但不能使用接口。

下面是一些建议,可以帮助您决定是使用接口还是抽象类为组件提供多态性。

If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created in that way. If a new version of an interface is required, you must create a whole new interface. If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes. If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class. If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.

抄袭: http://msdn.microsoft.com/en-us/library/scsyfw1d%28v=vs.71%29.aspx