我有这个
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
}
}
我该如何解决这种情况? 我不想在类操作数中使用泛型(因此我有操作数)因为我需要操作数是单一类型。在Integer的方法中我需要调用构造函数(new Integer(arg)),解决方案可能是以其他方式调用该方法。 溶液
答案 0 :(得分:2)
尝试重载方法
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);
}
}
答案 1 :(得分:1)
问题是您在Operand
中的方法声明,即<T extends Operand>
,您必须匹配&#34;合同&#34;与您的实施 -
class Integer extends Numeric {
@Override
public <T extends Operand> Operand operation(Operator operator, T operand) {
// Like this....
}
}
答案 2 :(得分:1)
在我看来,你想要这样的东西:
abstract class Operand<T, U> {
public abstract T operation(Operator operator, U operand);
}
abstract class Numeric<T, U> extends Operand<T, U> {
}
class Integer extends Numeric<Integer, Integer>
@Override
public Integer operation(Operator operator, Integer operand) {
}
}