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 wou
My two cents:
An interface basically defines a contract, that any implementing class must adhere to(implement the interface members). It does not contain any code.
On the other hand, an abstract class can contain code, and there might be some methods marked as abstract which an inheriting class must implement.
The rare situations I've used abstract classes is when i have some default functionality that the inheriting class might not be interesting in overriding, in say an abstract base class, that some specialized classes inherit from.
Example(a very rudimentary one!):Consider a base class called Customer which has abstract methods like CalculatePayment()
, CalculateRewardPoints()
and some non-abstract methods like GetName()
, SavePaymentDetails()
.
Specialized classes like RegularCustomer
and GoldCustomer
will inherit from the Customer
base class and implement their own CalculatePayment()
and CalculateRewardPoints()
method logic, but re-use the GetName()
and SavePaymentDetails()
methods.
You can add more functionality to an abstract class(non abstract methods that is) without affecting child classes which were using an older version. Whereas adding methods to an interface would affect all classes implementing it as they would now need to implement the newly added interface members.
An abstract class with all abstract members would be similar to an interface.