When to use an interface instead of an abstract class and vice versa?

前端 未结 23 2148
忘了有多久
忘了有多久 2020-11-22 04:29

This may be a generic OOP question. I wanted to do a generic comparison between an interface and an abstract class on the basis of their usage.

When wou

23条回答
  •  [愿得一人]
    2020-11-22 05:07

    Classes may inherit from only one base class, so if you want to use abstract classes to provide polymorphism to a group of classes, they must all inherit from that class. Abstract classes may also provide members that have already been implemented. Therefore, you can ensure a certain amount of identical functionality with an abstract class, but cannot with an interface.

    Here are some recommendations to help you to decide whether to use an interface or an abstract class to provide polymorphism for your components.

    • 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.

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

提交回复
热议问题