Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
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 (46k 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.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Apr 3, 2021 in Java by dante07 (13.1k points)

Browse Categories

...