不兼容的边界编译错误
public class Complex<T extends BigDecimal, R extends BigDecimal> {
private T r;
private R i;
public Complex(T r, R i) {
this.r = r;
this.i = i;
}
@Override
public String toString() {
return "Complex{" + "r=" + r + ", i=" + i + '}';
}
public T getR() {
return r;
}
public R getI() {
return i;
}
public Complex<T,R> add (Complex<T,R> other){
return new Complex<T,R>((T) (r.add(other.r)), (R) (i.add(other.i)));
}
}
然后调用类构造函数时:
Complex<BigDecimal,BigDecimal> s = new Complex<>(12121,12121);
出现这个编译错误:
cannot infer type arguments for Complex<>
reason: inference variable T has incompatible bounds
upper bounds: BigDecimal
lower bounds: Integer
where T is a type-variable:
T extends BigDecimal declared in class Complex
Java 不会将
int
隐式转换为 BigDecimal
,您需要显式向构造函数参数提供 BigDecimal 类型。
Complex<BigDecimal,BigDecimal> s = new Complex<>(BigDecimal.valueOf(12121),BigDecimal.valueOf(12121));