Can an abstract class have a constructor? Can an abstract class have a constructor? java java

Can an abstract class have a constructor?


Yes, an abstract class can have a constructor. Consider this:

abstract class Product {     int multiplyBy;    public Product( int multiplyBy ) {        this.multiplyBy = multiplyBy;    }    public int mutiply(int val) {       return multiplyBy * val;    }}class TimesTwo extends Product {    public TimesTwo() {        super(2);    }}class TimesWhat extends Product {    public TimesWhat(int what) {        super(what);    }}

The superclass Product is abstract and has a constructor. The concrete class TimesTwo has a constructor that just hardcodes the value 2. The concrete class TimesWhat has a constructor that allows the caller to specify the value.

Abstract constructors will frequently be used to enforce class constraints or invariants such as the minimum fields required to setup the class.

NOTE: As there is no default (or no-arg) constructor in the parent abstract class, the constructor used in subclass must explicitly call the parent constructor.


You would define a constructor in an abstract class if you are in one of these situations:

  • you want to perform someinitialization (to fields of theabstract class) before theinstantiation of a subclass actuallytakes place
  • you have defined final fields in theabstract class but you did notinitialize them in the declarationitself; in this case, you MUST havea constructor to initialize thesefields

Note that:

  • you may define more than oneconstructor (with differentarguments)
  • you can (should?) define all yourconstructors protected (making thempublic is pointless anyway)
  • your subclass constructor(s) cancall one constructor of the abstractclass; it may even have to call it(if there is no no-arg constructorin the abstract class)

In any case, don't forget that if you don't define a constructor, then the compiler will automatically generate one for you (this one is public, has no argument, and does nothing).


Yes it can have a constructor and it is defined and behaves just like any other class's constructor. Except that abstract classes can't be directly instantiated, only extended, so the use is therefore always from a subclass's constructor.