Interface vs Base class

后端 未结 30 3074
甜味超标
甜味超标 2020-11-21 07:34

When should I use an interface and when should I use a base class?

Should it always be an interface if I don\'t want to actually define a base implementation of the

30条回答
  •  情深已故
    2020-11-21 07:59

    Interfaces and base classes represent two different forms of relationships.

    Inheritance (base classes) represent an "is-a" relationship. E.g. a dog or a cat "is-a" pet. This relationship always represents the (single) purpose of the class (in conjunction with the "single responsibility principle").

    Interfaces, on the other hand, represent additional features of a class. I'd call it an "is" relationship, like in "Foo is disposable", hence the IDisposable interface in C#.

提交回复
热议问题