给出以下示例,为什么我需要在reciprocal()中使用doubleValue()(需要扩展Number类),因为java中有自动拆箱功能,可以将存储在num中的数字对象拆箱,并且可以计算num的倒数并返回双精度值?
class gen<T extends Number>{
T num ;
gen(T n ){
num = n ;
}
double reciprocal() {
return (1 / num.doubleValue()) ;
}
}
public class demo {
public static void main(String[] args) {
gen<Integer> ob = new gen<Integer>(5) ;
System.out.println(ob.reciprocal()) ;
}
}
而且,为什么我不能编写如下所示的相同代码? 附言:以下代码显示了reciprocal()方法中的错误:
class gen<T>{
T num ;
gen(T n ){
num = n ;
}
double reciprocal() {
return (1 / num) ;
// it shows error in the above step. it says "operator / is undefined
}
}
public class demo {
public static void main(String[] args) {
gen<Integer> ob = new gen<Integer>(5) ;
System.out.println(ob.reciprocal()) ;
}
}