I want to create an abstract Parameter class.
public abstract class Parameter{
}
I will have at least two subclasses:
public class ParamDouble extends Parameter{
public final double MIN;
public final double MAX;
private double value;
public ParamDouble(double min, double max, double current){
this.MIN = min;
this.MAX = max;
this.value = current;
}
public void setValue(double v) {
this.value = v;
}
public double getValue(){
return this.value;
}
}
and:
public class ParamInt extends Parameter{
public final int MIN;
public final int MAX;
private int value;
public ParamDouble(int min, int max, int current){
this.MIN = min;
this.MAX = max;
this.value = current;
}
public void setValue(int v) {
this.value = v;
}
public int getValue(){
return this.value;
}
}
So all subclasses will require, the finals MIN and MAX, and value, and contain three argument constructors, and setValue() and getValue(), but they have different types.
How can I declare these variables in the abstract class?
You only need a single generic class with the correct type bound:
Explanation of
<T extends Number & Comparable<T>>The bound of
TisNumber & Comparable<T>, which means it must be both aNumberand aComparable<T>. This is done becauseNumberdoes not implementComparable, which has thecompareTo()method, but all thejava.lang.Numberclasses (egInteger) do, and you need thecompareTo()method to check parameter range in thesetValue()method.Without this special bound, you can’t check the range generically.
The other major change was to make
minandmaxinstance variables, rather thanstaticones. You might consider having some static min/max values to pass into the constructor, or to implement subclasses like this: