I have a class that I want to be instantiated with either a String
or int
value, and I define the corresponding instance variable value
as generic type T
:
public class MathValue<T extends Object> {
private boolean isOperand, isOperator;
// a generic-typed instance variable:
private T value;
// constructor:
public MathValue(int operand) {
// compile-error -- "Incompatible types: required T, found Integer"
this.value = new Integer(operand);
this.isOperand = true;
this.isOperator = false;
}
// constructor:
public MathValue(String operator) {
// compile-error -- "Incompatible types: required T, found String"
this.value = operand;
this.isOperand = false;
this.isOperator = true;
}
}
I could very well have a single constructor instead, with a formal parameter of type T
, but I want to enforce the class' instantiation with a String
or int
argument:
public class MathValue<T extends Object> {
private boolean isOperand, isOperator;
// a generic-typed instance variable:
private T value;
// it totally works, but does not enforce specific-typed instantiation:
public MathValue(T operandOrOperator) {
this.value = operandOrOperator;
if (operandOrOperator instanceof Integer) {
this.isOperand = true;
this.isOperator = false;
} else if (operandOrOperator instanceof String) {
this.isOperand = false;
this.isOperator = true;
}
}
}
So despite the logical error of wanting to make a generic-typed class "not so generic", is it possible to instantiate a generic variable with a specific-typed value?