Why are interfaces preferred to abstract classes?

前端 未结 23 1463
鱼传尺愫
鱼传尺愫 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条回答
  •  Happy的楠姐
    2020-12-02 07:09

    In general, and this is by no means a "rule" that should be blindly followed, the most flexible arrangement is:

    interface
       abstract class
           concrete class 1       
           concrete class 2
    

    The interface is there for a couple of reasons:

    • an existing class that already extends something can implement the interface (assuming you have control over the code for the existing class)
    • an existing class can be subclasses and the subclass can implement the interface (assuming the existing class is subclassable)

    This means that you can take pre-existing classes (or just classes that MUST extend from something else) and have them work with your code.

    The abstract class is there to provide all of the common bits for the concrete classes. The abstract class is extended from when you are writing new classes or modifying classes that you want to extend it (assuming they extend from java.lang.Object).

    You should always (unless you have a really good reason not to) declare variables (instance, class, local, and method parameters) as the interface.

提交回复
热议问题