2017-08-26 40 views
2

我是初学java,我读这本书的“Java初学者指南”和generics.The作者的主题创建下列通用类:的Java:泛型输入类型兼容性

// In this version of NumericFns, the type argument 
// for T must be either Number, or a class derived 
// from Number. 
class NumericFns<T extends Number> { 
    T num; 
    // Pass the constructor a reference to 
    // a numeric object. 
    NumericFns(T n) { 
     num = n; 
    } 

在这种情况下, ,类型参数 必须是Number的一个子类或 。

// Return the reciprocal. 
    double reciprocal() { 
     return 1/num.doubleValue(); 
    } 
    // Return the fractional component. 
    double fraction() { 
     return num.doubleValue() - num.intValue(); 
    } 
    // ... 
} 

和笔者说,如果我们补充说,检查数值的绝对值存储在两个通用的对象,如下面的新方法:

// This won't work! 
// Determine if the absolute values of two objects are the same. 
boolean absEqual(NumericFns<T> ob) { 
    if(Math.abs(num.doubleValue()) == 
      Math.abs(ob.num.doubleValue()) return true; 
    return false; 
} 

而且说明它写的是:

在这里,使用标准方法Math.abs()来获得每个数字的绝对值, 然后将这些值进行比较。这种尝试的麻烦在于它只能与 其他类型与调用对象相同的NumericFns对象一起工作。例如,如果 调用对象的类型为NumericFns<Integer>,那么参数ob也必须是 NumericFns<Integer>。例如,它不能用于比较NumericFns<Double>, 类型的对象。因此,这种方法不会产生一般的(即通用的)解决方案。

我不明白为什么它不能正常工作所有不同的类型。 请帮忙。

回答

3

这是因为absEqual(NumericFns<T> ob)中的T与构造函数中的T相同,如果该方法在同一个类中。这就是为什么如果使用不同的NumericFns其中T是一次Integer而一旦Double,您可以:

error: incompatible types: NumericFns<Double> cannot be converted to NumericFns<Integer> 

相反,你可以使用:

// This will work! 
// Determine if the absolute values of two objects are the same. 
boolean absEqual(NumericFns<? extends Number> ob) { 
    if(Math.abs(num.doubleValue()) == 
      Math.abs(ob.num.doubleValue())) return true; 
    return false; 
} 
+0

现在我知道了,谢谢。 –