Why are interfaces preferred to abstract classes?

前端 未结 23 1496
鱼传尺愫
鱼传尺愫 2020-12-02 06:23

I recently attended an interview and they asked me the question \"Why Interfaces are preferred over Abstract classes?\"

I tried giving a few answers like:

23条回答
  •  臣服心动
    2020-12-02 07:14

    interface is not substitute for abstract class.

    Prefer

    interface: To implement a contract by multiple unrelated objects

    abstract class: To implement the same or different behaviour among multiple related objects


    Refer to this related SE question for use cases of both interface and abstract class

    Interface vs Abstract Class (general OO)

    Use case:

    If you have to use Template_method pattern, you can't achieve with interface. Abstract class should be chosen to achieve it.

    If you have to implement a capability for many unrleated objects, abstract class does not serve the purpose and you have to chose interface.

提交回复
热议问题