Since we can't instantiate an abstract class, then what is the necessity of having constructors in abstract class?
-
2http://stackoverflow.com/questions/260666/abstract-class-constructor-in-java – tim_yates Jul 02 '10 at 08:45
4 Answers
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).

- 1
- 1
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...
}

- 35,279
- 21
- 87
- 141

- 50,101
- 39
- 117
- 168
We can use a abstract class constructor to execute code that is relevant for every subclass. This way preventing duplicate code

- 1,232
- 1
- 12
- 26
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

- 887
- 1
- 6
- 17