What's the difference between an abstract class and an interface?

This question already has an answer here:

  • Interface or abstract class? 15 answers

  • There are technical differences between Abstract Classes and Interfaces, that being an Abstract Class can contain implementation of methods, fields, constructors, etc, while an Interface only contains method and property prototypes. A class can implement multiple interfaces, but it can only inherit one class (abstract or otherwise).

    However, in my opinion, the most important difference between Interfaces and Abstract Classes is the semantic difference.

    An Interface defines what something can do (how it behaves), and an Abstract Class defines what something is.

    Take for example IEnumerable , the semantic meaning behind this is that anything that implements IEnumerable is enumable, it doesn't mean that it's an enumeration, but that it can behave like one (can be enumerated).

    Contrast that with the washing machine example, anything that inherits it is a type of washing machine. Anything that inherits it would be a type of washing machine, a top loader, or side loader, etc.

    Instead, if you had an interface called ICanWash , which could contain a method called Wash . You could have various things implement ICanWash , be it a Person , an abstract washing machine class, etc, where the actual implementation does not matter, just you need to know that the behavior is that it can wash things.

    In summary, classes define what something is, interfaces define what something can do.


    From MSDN:

    By using interfaces, you can, for example, include behavior from multiple sources in a class. That capability is important in C# because the language doesn't support multiple inheritance of classes

    So, use interface if you want that any class can inherit that methods.

    From same MSDN page:

    In addition, you must use an interface if you want to simulate inheritance for structs, because they can't actually inherit from another struct or class.


    Interface allows a class to inherit/implement more than one interface, while in C# you can only inherit from one class.

    Multiple inheritance, basically.

    链接地址: http://www.djcxy.com/p/54244.html

    上一篇: 接口和类的区别

    下一篇: 抽象类和接口之间有什么区别?