我有以下 Duple 类,我正在尝试编写方法来对其两个“单元格”执行数学运算 ((new Duple(1,2)).plus(new Duple(2,6 ) == new Duple(3,8))
:
final class Duple<T,U> {
final T a;
final U b;
public Duple(T a, U b) { this.a = a; this.b = b; }
public String toString() {
return "(" + a + ", " + b + ")";
}
/*public Duple<T,U> plus(Duple <T,U> otherDuple) {
return Duple(a + otherDuple.a, b + otherDuple.b);
}*/
注释掉的代码会出错,因为它不能保证 T
或 U
支持 +
。有没有办法让它对参数进行编译时检查?
我尝试过:
public Duple<T,U> plus(Duple <T extends Number,U extends Number> otherDuple) { ... }
但是编译器提示我删除extends
。我看到了一个使用用户定义接口(interface)的示例,但对于我需要它的用途来说,这似乎很极端。
基本上我正在尝试模仿:
plus :: (Num t, Num u) => Duple t u -> Duple t u -> Duple t u
(x1,y1) `plus` (x2,y2) = (x1 + x2,y1 + y2)
如果它是用 Haskell 编写的
最佳答案
您不能拥有仅存在于类的某些实例中的方法。
相反,您可以对类的类型参数施加约束。
关于java - 如何限制方法仅接受具有某些限制的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27261950/