Why and when should we use an abstract class?
Let's start with what exactly an abstract class is:
Basically an abstract class is a class that is declared as abstract. It contains abstract methods. We can not create an instance of an abstract class.
Then why do we use abstract classes?
1. To follow a base class
The first and main reson to use an abstarct class is we can create a base class and inherit the child classes from it. This implies the important feature of Object Oriented Programminng i.e. Inheritance.
**2. To remove code duplication. **
Then why not to use interfaces?
We can provide some implementaion in abstarct class methods where as interfaces can not have that. We can override the implemented methods in child classes if needed.
The child classes will implement all the methods and varaibles written in an abstract class, so there is no need to write the same code in each subclass eliminating code duplication.
But in this case we can easily use non-abstract i.e. concrete classes. Then why should we use abstarct classes?
As we know we can not instantiate abstract classes, so if the requirement is not to let the user instantiate or base class then abstract class is best to have.
Also abstract classes can have public, private,protected access modifiers where as interfaces can have only default access modifier.