"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Can Abstract Classes Have Constructors?

Can Abstract Classes Have Constructors?

Posted on 2025-02-06
Browse:835

Can Abstract Classes Have Constructors?

Can Abstract Classes Possess Constructors?

Despite the abstract nature of abstract classes, they indeed support the presence of constructors.

Utilization and Purposes of Abstract Class Constructors

An abstract class constructor serves various purposes:

  1. Enforcement of Class Constraints: Abstract constructors enforce constraints by ensuring that subclasses adhere to certain rules or provide minimum fields necessary for object initialization.
  2. Initialization of Fields: They allow abstract classes to initialize shared fields that all subclasses inherit and utilize.
  3. Overloading: Abstract constructors facilitate constructor overloading, enabling subclasses to define specific constructors tailored to their requirements, while still benefiting from the shared fields provided by the abstract class's constructor.

Example

Consider the following code snippet:

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);
    }
}

In this example, the abstract class Product possesses a constructor that sets the multiplyBy field. The subclasses TimesTwo and TimesWhat override this constructor to provide customized initialization.

Note:

It's crucial to note that abstract classes do not possess default constructors, so subclasses must explicitly invoke the parent constructor using super.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3