0 votes
1 view
in Java by (3.4k points)

Can an abstract class have a constructor?

If so, how can it be used and for what purposes?

1 Answer

0 votes
by (46.1k points)

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

abstract class Product { 

    int multiplyBy;

    public Product( int multiplyBy ) {

        this.multiplyBy = multiplyBy;

    }

    public int multiply(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 holds a constructor. The concrete class TimesTwo holds a constructor that just hardcodes the value 2. The concrete class TimesWhat holds a constructor that allows the caller to specify the value.

Abstract constructors will constantly be used to support class constraints or invariants such as the least fields required to set up the class.

You must not that there's no default (or no-arg) constructor in the parent abstract class, the constructor applied in a subclass must explicitly call the parent constructor.

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...