Nowadays, in an interview no one asks direct questions; rather, they will give you a scenario and ask the solution for the same. And almost always there is one common question which you encounter in almost all interviews: "Where will you use Interface and Abstract class?" Or the interviewer will give one scenario and ask in this scenario if you will go for Abstract class or Interface and why.
My idea is to give readers an understanding of where to user Interface and Abstract class but also to give an understanding in detail as well. Because both the concepts are very important.
So let’s start with Abstract Class
Abstract Class
The purpose of abstract class is to provide the default functionality for its base class. You need to put the abstract keyword ahead of class to define as Abstract Class as mentioned below,
- public abstract class AbstractCar
- {
-
- }
You can have both abstract and non-abstract methods in the Abstract Class. Generally we use abstract class as a base class. But you need to implement all the abstract methods in the deriver class by using override keyword. You can’t create an object of Abstract Class. Abstract class can never support multiple inheritances.
Let’s see the details example of abstract class
Now we move on and see a few important things about “Abstract Class,” let’s take it one by one.
- We will try to create an object of Abstract Class and see what happens.
So that means we can’t create an object of Abstract Class.
- Interface will not provide any access specifier to the abstract method,
It means in abstract class, abstract methods are not public by defaul, it's private by default. The access modifier of the abstract method should be the same in both the abstract class and in its derived class. If you declare an abstract method as protected, it should be protected in its derived class. Otherwise, the compiler will raise an error.
- Like interface will not provide any access specifier to the abstract method :
We can define Delegates, Properties etc. in Abstract Class.
- Abstract Properties
- You need to implement all the abstract methods in derived class,
I got the above error because I have not implemented all the methods in the derived class. So it’s mandatory to implement all the abstract methos and properties in the derived class.
Conclusion
I hope this article helps you to explore all the possibilities of Abstract Class. In case not, please drop a note and I will explore it further. In the second article I will talk about Interface and will give more focus on where to use it.