Why are interfaces preferred to abstract classes?

前端 未结 23 1497
鱼传尺愫
鱼传尺愫 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:10

    Abstract classes have a number of potential pitfalls. For example, if you override a method, the super() method is not called unless you explicitly call it. This can cause problems for poorly-implemented overriding classes. Also, there are potential problems with equals() when you use inheritance.

    Using interfaces can encourage use of composition when you want to share an implementation. Composition is very often a better way to reuse others objects, as it is less brittle. Inheritance is easily overused or used for the wrong purposes.

    Defining an interface is a very safe way to define how an object is supposed to act, without risking the brittleness that can come with extending another class, abstract or not.

    Also, as you mention, you can only extend one class at a time, but you can implement as many interfaces as you wish.

提交回复
热议问题