This is the most widely asked question in the interviews. A fresher or an experienced professional, either way, you would come across this question.
Difference between these two always coincides and the interviewer stresses particularly on this question to understand how good you are at understanding the concepts and implementing them.
We all know the theoretical part of what an Abstract class is and what an Interface is.
Why Abstract Class?
Because it has the implementation, without which it would act same as Interface.
Why Interface?
Because it has functionality that a class or struct can implement.
I've come with an example to explain in what scenarios the abstract class and interface work.
Example
- public class Doctors {
- public string Diagnose() {
- return "I have Diagnosed a disease";
- }
- public string Treatment() {
- return "I have treated this disease";
- }
- public string Medication() {
- return "I have prescribed medications";
- }
- }
Consider we have a separate class for each Doctor.
- public class Physician: Doctors {
-
- }
- public class Orthopedician: Doctors {
-
- }
- public class Neurologist: Doctors {
-
- }
We need a method for inheriting the Surgery feature for Orthopedician and Neurologist. Though both are specialized surgeons, their operation process might be different.
So, we create an abstract class in which the method will be declared as Abstract and it should be implemented in child classes.
- public abstract class Surgeon {
- public abstract string Surgery();
- }
Now, we are trying to inherit from this abstract class and the kind of Surgery is implemented by Orthopedician and Neurologist.
- public class Orthopedician: Doctors, Surgeon {
- public override string Surgery() {
- return "I have done surgery for joints ";
- }
- }
- public class Neurologist: Doctors, Surgeon {
- public override string Surgery() {
- return "I have done surgery for the brain";
- }
- }
In the above two classes, Orthopedician and Neurologist are trying to inherit from Doctors and Surgeon class, which can't be done because an abstract class cannot support multiple inheritances.
Here. we need to use Interface to achieve the above concept.
- interface ISurgeon
- {
- string GetSurgery();
- }
The implementation is given below.
- public class Orthopedician: Doctors, ISurgeon {
- public string GetSurgery() {
- return "I have done surgery for joints";
- }
- }
- public class Neurologist: Doctors, ISurgeon {
- public string GetSurgery() {
- return "I have done surgery for brain";
- }
- }