Can abstract classes also have constructors?

Asked 2 years ago, Updated 2 years ago, 147 views

Can abstract classes also have constructors? If you can, how do you use it and why?

java constructor abstract-class

2022-09-22 13:09

1 Answers

Yes, abstract classes can also have constructors.

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 parent class Product is an abstract class and has a constructor. And the TimesTwo class that inherits the Product has a constructor, which is called super(2); Then, move on to the creator of the inherited product and substitute 2 for multiBy. Similarly, in TimesWhat, which inherited the Product, the constructor calls the constructor of the higher class, and equally passes what to the constructor of the Product, so that MultiplyBy is initialized to what.

Usually, the constructor of an abstract class is used to give the class some constraint.


2022-09-22 13:09

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.