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

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


当前回答

纯粹在继承的基础上,你可以使用一个抽象的定义清晰的后代,抽象的关系(例如动物->猫)和/或需要继承虚拟或非公共属性,特别是共享状态(接口不支持)。

你应该尝试使用组合(通过依赖注入)而不是继承,并且注意接口作为契约支持单元测试、关注点分离和(语言变化)多重继承,而抽象则不能。

其他回答

如果我们有一个对所有派生类都相同的实现,那么此时最好使用抽象类而不是接口。当我们有一个接口时,我们可以将我们的实现移动到任何实现接口的类。在抽象类中,它避免了代码重复,并共享所有派生类的实现。接口允许开发松散耦合的系统,这有助于更好的测试。

当您需要向一组(相关或不相关的)对象添加额外的功能时,接口比抽象类表现得更好。如果你不能给他们一个基本抽象类(例如,他们是密封的或已经有一个父类),你可以给他们一个虚拟的(空的)接口,然后简单地为这个接口编写扩展方法。

抽象类可以有实现。

接口没有实现,它只是定义了一种契约。

也可能存在一些依赖于语言的差异:例如c#没有多重继承,但在一个类中可以实现多个接口。

简单的回答是:抽象类允许您创建子类可以实现或覆盖的功能。接口只允许您定义功能,而不能实现它。虽然一个类只能扩展一个抽象类,但它可以利用多个接口。

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

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

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