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?
in java you can inherit from one (abstract) class to "provide" functionality and you can implement many interfaces to "ensure" functionality
1.If you are creating something that provides common functionality to unrelated classes, use an interface.
2.If you are creating something for objects that are closely related in a hierarchy, use an abstract class.
When to do what is a very simple thing if you have the concept clear in your mind.
Abstract classes can be Derived whereas Interfaces can be Implemented. There is some difference between the two. When you derive an Abstract class, the relationship between the derived class and the base class is 'is a' relationship. e.g., a Dog is an Animal, a Sheep is an Animal which means that a Derived class is inheriting some properties from the base class.
Whereas for implementation of interfaces, the relationship is "can be". e.g., a Dog can be a spy dog. A dog can be a circus dog. A dog can be a race dog. Which means that you implement certain methods to acquire something.
I hope I am clear.
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 likeGetName()
,SavePaymentDetails()
.Specialized classes like
RegularCustomer
andGoldCustomer
will inherit from theCustomer
base class and implement their ownCalculatePayment()
andCalculateRewardPoints()
method logic, but re-use theGetName()
andSavePaymentDetails()
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.