3

Since we can't instantiate an abstract class, then what is the necessity of having constructors in abstract class?

JavaUser
  • 22,494
  • 44
  • 98
  • 127

4 Answers4

4

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).

Community
  • 1
  • 1
2

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...
}
Rob Stevenson-Leggett
  • 33,849
  • 21
  • 84
  • 138
izb
  • 45,586
  • 39
  • 110
  • 165
2

We can use a abstract class constructor to execute code that is relevant for every subclass. This way preventing duplicate code

Bas
  • 1,222
  • 1
  • 11
  • 26
1

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

CheesePls
  • 887
  • 1
  • 6
  • 17