Why prefer interfaces to abstract classes?

In many cases, interfaces are preferable over abstract classes. We might wonder why interfaces are preferable compare to abstract classes then we should know some facts. Following are some facts about interfaces over abstract classes:

Facts about interfaces

  • Existing classes can be easily retrofitted to implement a new interface.
  • Interfaces are ideal for defining mixins.
  • Interfaces allow the construction of nonhierarchical type frameworks.
  • Interfaces enable safe, powerful functionality enhancements via the wrapper class idiom

If we make an abstract class rather than an interface, A class that inherits the abstract class can’t also inherit a different abstract class.

  • An abstract class can have a shared state or functionality. An interface only provides the state or functionality.
  • An abstract class will reduce the code that has to be rewritten because it’s functionality or state can be shared. The interface has no defined information to be shared.
  • In the case of interface, we specify what the object can do. In the case of an abstract class, we specify what an object is.
  • The interface provides “HAS A” capability. The abstract class establishes “IS A” relation.

Use abstract classes when:

  • We want to share code among several closely related classes.
  • We expect that classes that extend the abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
  • We want to declare non-static or non-final fields.

Use interfaces when:

  • We expect that unrelated classes would implement the interface.
  • We want to specify the behaviour of a particular data type, but not concerned about who implements its behaviour.
  • We want to take advantage of multiple inheritances of type.

Reference

https://stackoverflow.com/questions/639592/why-are-interfaces-preferred-to-abstract-classes

https://stackoverflow.com/questions/479142/when-to-use-an-interface-instead-of-an-abstract-class-and-vice-versa

https://stackoverflow.com/questions/18777989/how-should-i-have-explained-the-difference-between-an-interface-and-an-abstract