It’s one of the commonly asked questions in interview to know understanding of Interface and Abstract class. Generally developers know about what they are as per syntax and basic behaviors ; but which one to use when- is bit confusing to most of developers. Let’s try to understand it in better way. I have divided it in two parts, in first part I’ll talk more of design considerations and purposes of these two to set the context; in next part we will see practical approach with sample code.
Let’s dive in to the point without wasting much of time. So here is the thumb rule you need to understand first:-
- Interfaces provide ‘as a’ or ‘can do’ relationship. So interfaces are meant for implementation of unrelated responsibilities.
- Abstract classes are meant for base class. So if you have abstract class and you have one or more class(s) which is/are inheriting abstract class, then they make ‘is a’ relationship between parent and child class.
If you keep above points in mind then you will understand it fully that purposes of these two are absolutely different. Here are some of the conclusions on the basis of these core purposes of these two.
- Interfaces do not provide inheritance unlike Abstract class. So if you create multiple interfaces, it’s perfectly alright to implement all those in one class. Because they are having ‘can do’ relationships; so despite of having absolutely unrelated responsibilities you can have those interfaces implemented in a class. That’s the reason multiple implementation is possible and logical with interfaces in C#.
- On other hand side Abstract classes are meant to be base/parent class. So they make ‘is a’ relationship with children classes. So logically and from design perspective it’s not proper that you have multiple classes as parent class for one child class.
I hope it helps you to understand these two better from design perspective. In next part of it I’ll focus on practical differences between Interface and Abstract classes with examples and code samples.