我有这个
abstract class Operand {
public abstract <T extends Operand> Operand operation(Operator operator, T operand);
}
abstract class Numeric extends Operand {
}
class Integer extends Numeric
@Override
public <Integer> Operand operation(Operator operator, Integer operand) {//problem
}
}
我该如何解决这种情况? 我不想在类 Operand 中使用泛型(所以我有 Operand),因为我需要 Operand 是单一类型。在 Integer 的方法内部,我需要调用构造函数(new Integer(arg)),解决方案可能是以其他方式调用该方法。 解决方案?
最佳答案
尝试使用重载方法
abstract class Operand {
public abstract <T extends Operand> Operand operation(Operator operator, T operand);
}
abstract class Numeric<T extends Numeric<T>> extends Operand {
public abstract Operand operation(Operator operator, T operand);
}
class Integer extends Numeric<Integer> {
@Override
public Operand operation(Operator operator, Integer operand) {
// add your Integer specific code here
return null; // replace null with actual returned value
}
@Override
public <T extends Operand> Operand operation(Operator operator, T operand) {
// simply call to overridden Integer specific method
// no harm to downcast it here
return operation(operator, (Integer) operand);
}
}
关于JAVA:类型参数隐藏类类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23571861/