Home >Java >javaTutorial >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:
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.
The above is the detailed content of Can Abstract Classes Have Constructors?. For more information, please follow other related articles on the PHP Chinese website!