Reputation: 46641
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:
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.
Upvotes: 4
Views: 2389
Reputation: 58753
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.
Upvotes: 6
Reputation: 499132
The interface would define the contract. Any implementer (either directly or via an abstract implementer) would conform to this contract.
An abstract class means you could reuse parts of an implementation across concrete implementations - you could have more than one abstract class, implemented differently.
Upvotes: 2
Reputation: 51711
I'm assuming C# here because the other question had a C# tag
The obvious benefit is that in the future you have another class, that already inherits from a base class, and you want to pass that to a method that accepts the . . .
You can't do put first base class in there, because C# doesn't all multiple inheritance, so you can never pass object that subclasses a different class in there.
You can however put interface in there, because the new object can always implement the Interface, even if it logically should derive from the base class.
Having both means the base class can implement the interface, that suits you now because you can put common logic in there, you don't need to repeat yourself, or have a heap of static methods in a "helper" class.
Also in the future if you have other classes that you want to use, they don't have to inherit the base class, then can just implement the interface.
Hope this makes sense :)
Upvotes: 1