Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Benefit of having an abstract class implement an interface?

I recently asked this question on if I should implement interfaces or abstract classes. Scottm gave answer suggesting I use both, but I am still unsure why I would want to do this. Is there a benefit in the long term? What are advantages of doing it that way?

Here are some benefits I think:

  • I can add methods to abstract class without breaking the implementation, but with interfaces, I would break it.
  • I can inherit from multiple interfaces, but only one abstract class
  • Abstract class allows me to define standard behavior, but override it if I want to.

Here is another question. If I implement an interface, should the interface only contain methods that all sub-classes can do? And if I need extra logic, I would create a concrete class or abstract class with more specific implementations.

like image 776
Xaisoft Avatar asked Jan 19 '23 15:01

Xaisoft


1 Answers

This approach gives you the best of both worlds - the flexibility of interfaces with the helpful option of a base class.

By requiring only that consumers implement your interface, you are not forcing them to lose the only inheritance slot open to their class (C# not allowing multiple inheritance).

But by additionally offering an abstract base class, you can give them a "leg up", perhaps by implementing some helper functionality that is likely to be a common requirement to most implementations of your interface - for example this could be achieved using a Template Method pattern.

There are several examples in the .NET Framework itself of both an interface and a base class being exposed. For example System.ComponentModel.IComponent and System.ComponentModel.Component

Here is another question. If I implement an interface, should the interface only contain methods that all sub-classes can do?

Yes. You're essentially describing the Interface Segregation Principle.

like image 56
Ian Nelson Avatar answered Feb 16 '23 10:02

Ian Nelson