Most of the new developers are always confused as when, where and why we should use an interface or an abstract class.Although both abstract classes and interfaces serve the same purpose to some extent but yet they are different in many terms.
Although both act as a sort of contract but there are some major differences in both of them which i will sum up in this article
- Interfaces belong to interface type where as abstract classes belong to class type
- Interface contain only abstract methods which the type who implements the interface should give its declaration whereas abstract class may contain both abstract methods as well as concrete methods.
- Abstract class can extend another class and implement multiple interfaces, where as an interface cannot be inherited from a class.
- If A is your abstract class and B is a class which extends A, then in this situation you can have B only extend from A not from any other class i.e no direct multiple inheritance is supported and this in a sense is achieved by interfaces as we can implement any no of interfaces for a given class.
- Both follow a different paradigm as interfaces are implemented whereas classes are extended.
So both concepts are a kind of generalization and are used in situations where we cannot in reality define the object which we are talking about this line means for example if we say a car then its a very general specification and no such entity exists in real which we can say is a car.But if you say “Ferrari” then it does make sense and you can identify a unique instance.
So to define car’s action we can use either abstract classes or interfaces to declare the general car functionalities.
After doing that we can go ahead and create a Ferrari class which either can derive from your abstract class or can implement the interface created by you.
Using abstract classes or interfaces totally depends on what type of inheritance are you following if your applications is sounding to use multiple inheritance then its always better to go with interfaces and if you know that with a particular class the derived class need not be derived from another class then you can go ahead with abstract classes.
These are the main differences and some similarities between these two.If you want to add something else do leave a comment.