When to Use Interfaces?

An interface defines a type with an abstract contract. An abstract class also defines a type with an abstract contract. Which should you use and when?

There are two major differences between interfaces and abstract classes:

  1. Interfaces provide a form of multiple inheritance, because you can implement multiple interfaces. A class can extend only one other class, even if that class has only abstract methods.

  2. An abstract class can have a partial implementation, protected parts, static methods, and so on, whereas interfaces are limited to public constants and public methods with no implementation.

These differences usually direct the choice of which tool is best to use in a particular implementation. If multiple inheritance is important or even useful, interfaces are used. However, an abstract class enables you to provide some or all of the implementation so that it can be inherited easily, rather than by explicit forwarding.

Any major class you expect to be extended, whether abstract or not, should be an implementation of an interface. Although this approach requires a little more work on your part, it enables a whole category of use that is otherwise precluded. For example, suppose we had created an Attributed class instead of an Attributed interface with an AttributedImpl implementation class. In that case, programmers who wanted to create new classes that extended other existing classes could never use Attributed, since you can extend only one classthe class AttributedBody could never have been created. Because Attributed is an interface, programmers have a choice: They can extend AttributedImpl directly and avoid the forwarding, or, if they cannot extend, they can at least use composition and forwarding to implement the interface. And if the general implementation provided is incorrect, they can write their own implementation. You can even provide multiple possible implementations of the interface to prospective users. Whatever implementation strategy programmers prefer, the objects they create are Attributed.

We Are Founder..