Friday, December 28, 2018

java - Can an abstract class have a constructor?




Can an abstract class have a constructor?



If so, how can it be used and for what purposes?


Answer



Yes, an abstract class can have a constructor. Consider this:



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.



No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...