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

前端 未结 23 2182
忘了有多久
忘了有多久 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:19

    Purely on the basis of inheritance, you would use an Abstract where you're defining clearly descendant, abstract relationships (i.e. animal->cat) and/or require inheritance of virtual or non-public properties, especially shared state (which Interfaces cannot support).

    You should try and favour composition (via dependency injection) over inheritance where you can though, and note that Interfaces being contracts support unit-testing, separation of concerns and (language varying) multiple inheritance in a way Abstracts cannot.

提交回复
热议问题