patternjavaCritical
Can an abstract class have a constructor?
Viewed 0 times
constructorabstracthaveclasscan
Problem
Can an abstract class have a constructor?
If so, how can it be used and for what purposes?
If so, how can it be used and for what purposes?
Solution
Yes, an abstract class can have a constructor. Consider this:
The superclass
Abstract constructors will frequently be used to enforce class constraints or invariants such as the minimum fields required to setup the class.
NOTE: As there is no default (or no-arg) constructor in the parent
abstract class, the constructor used in subclass must explicitly call
the parent constructor.
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 superclass
Product is abstract and has a constructor. The concrete class TimesTwo has a constructor that just hardcodes the value 2. The concrete class TimesWhat has a constructor that allows the caller to specify the value.Abstract constructors will frequently be used to enforce class constraints or invariants such as the minimum fields required to setup the class.
NOTE: As there is no default (or no-arg) constructor in the parent
abstract class, the constructor used in subclass must explicitly call
the parent constructor.
Code Snippets
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);
}
}Context
Stack Overflow Q#260666, score: 757
Revisions (0)
No revisions yet.