This may be a generic OOP question. I wanted to do a generic comparison between an interface and an abstract class on the basis of their usage.
When would one want to use an interface and when would one want to use an abstract class?
This may be a generic OOP question. I wanted to do a generic comparison between an interface and an abstract class on the basis of their usage.
When would one want to use an interface and when would one want to use an abstract class?
An abstract class can have implementations.
An interface doesn't have implementations, it simply defines a kind of contract.
There can also be some language-dependent differences: for example C# does not have multiple inheritance, but multiple interfaces can be implemented in a class.
I wrote an article about that:
Abstract classes and interfaces
Summarizing:
When we talk about abstract classes we are defining characteristics of an object type; specifying what an object is.
When we talk about an interface and define capabilities that we promise to provide, we are talking about establishing a contract about what the object can do.
This can be a very difficult call to make...
One pointer I can give: An object can implement many interfaces, whilst an object can only inherit one base class( in a modern OO language like c#, I know C++ has multiple inheritance - but isn't that frowned upon?)
Basic thumb rule is: For "Nouns" use Abstract class and for "Verbs" use interface
E.g:
car
is an abstract class anddrive
, we can make it an interface.Consider using abstract classes if any of these statements apply to your situation:
Consider using interfaces if any of these statements apply to your situation:
Source
An abstract class can have shared state or functionality. An interface is only a promise to provide the state or functionality. A good abstract class will reduce the amount of code that has to be rewritten because it's functionality or state can be shared. The interface has no defined information to be shared