3

I have been asked the following question in an interview: "What is the need of an interface when you can have an abstract method within an abstract class?" Which I did not know the answer to.

Could you provide an example why and when it may be useful?

7

You can't use multiple inheritance with abstract classes in C#. But it is possible to derive from multiple interfaces, which leads to scenarios where it can be necessary to use an interface instead of an abstract class for a new method.

3

Besides not being able to use multiple inheritance, as Robert Harvey has pointed out, when using an abstract class, you usually do so to group common behaviour of children of this supertype together, respecting the DRY principle.

But by doing so, you are sometimes introducing more data to the class than the single interface would probably need for it to function (not always, but it can happen).

This leads to the need of instantiating larger classes than possible to use it for a very simple task, because you need to pass the abstract class, instead of having an interface and a simpler class, providing the implementation with only the necessary details to fulfill the contract.

3

When an API uses an abstract base class, the (only) way to provide a version of that API is to subclass the abstract base class.

Because in C# and Java we can only have one super class, it is, in some sense, a scarce resource. Requiring that each API implementer subclass from that abstract base class means they cannot subclass from a class of their choice. (This means the subclass will then have be a new class for each implementer, and that will likely have to act as a proxy to another class in the their hierarchy.)

When an API uses an interface, each implementer may choose any base class they desire. This means, for example, that they can implement the interface from an existing class in their class hierarchy.

Thus, interfaces result in looser coupling (among class hierarchies) and more implementation freedom.

(There are further things to say about tighter coupling if the abstract class provides any implementation, e.g. anything beyond the abstract method).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.