I see code where an abstract class implements an interface? Why would you do that? Instead of putting abstract members in interface we can directly put them in the interface right ?
Why would one write such code? What is the purpose or need?
An interface is simply a contract to other code. An abstract class on the other hand, can be much more. They can:
One good example of a use case for this is found in the template method pattern. You could have an interface for a command:
public interface IMyCommand
{
void Execute();
}
And you have a set of commands that follows a certain sequence. To enforce that, you could have them derive from an abstract base class:
public abstract class MyTemplateClass : IMyCommand
{
public void Execute()
{
MyProcessFirst();
MyProcessSecond();
}
protected abstract void MyProcessFirst();
protected abstract void MyProcessSecond();
}
Now you can have objects that follow the template method derive from the abstract base class, and others just implement the interface.
Instead of putting abstract members in interface we can directly put them in the interface right ?
Not with an implementation we can't.
Because we can have part of the implementation in the abstract class, we can get all of the advantages of reuse.
We could though ask the opposite; why not just have the abstract class and no interface.
Often, especially with private or internal combinations of abstract class and interface it would indeed be an improvement to do this. But there are still some advantages to interfaces that abstract classes don't have.
An obvious one is if we have, or are likely to have, implementations that aren't derived from that abstract class. Another is to take advantage of variance in the interface, which the class can't do.
Even if we don't have any cases now that implement the interface but not via the abstract class, it's worth considering if we might, if the interface is public (YAGNI applies very differently to public interfaces where it will be a breaking change to remove anything).
Related to that, it can be a useful combination to have a public interface that client code may implement as well as your code, and an abstract class used in the implementations you provide, because it contains commonality to your implementations that wouldn't necessarily be common to other people's implementations. Perhaps you would allow other people to inherit from it too, without insisting on it, or perhaps you would have only internal
constructors so only your code can use it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With