This question already has an answer here:
- Can an abstract class have a constructor? 21 answers
Since we can't instantiate an abstract class, then what is the necessity of having constructors in abstract class?
This question already has an answer here:
Since we can't instantiate an abstract class, then what is the necessity of having constructors in abstract class?
Abstract classes are designed to be extended, each constructor from the child must perform a call to a constructor from the base class, thus you need constructors in your abstract class.
The abstract class is a skeleton and thus makes no sense to instantiate it directly since it is still incomplete (children will provide the rest).
We can use a abstract class constructor to execute code that is relevant for every subclass. This way preventing duplicate code
An example:
public abstract class BaseClass
{
private String member;
public BaseClass(String member)
{
this.member = member;
}
... abstract methods...
}
public class ImplementingClass extends BaseClass
{
public ImplementingClass(String member)
{
/* Implementing class must call a constructor from the abstract class */
super(member);
}
... method implementations...
}
Abstract classes can have fields and non-abstract methods(what makes it an abstract class rater than an interface). The fields probably need to be initialized when a class that extends it is instantiated.
Having a constructor in the abstract class allows you to call super(foo);
to initialize them as opposed to doing it directly