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:
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.
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