Java The Complete Reference, Seventh Edition

(Greg DeLong) #1
for(int i=0; i < nums.length; i++)
sum += nums[i].doubleValue(); // Error!!!

return sum / nums.length;
}
}


InStats, theaverage( )method attempts to obtain thedoubleversion of each number in
thenumsarray by callingdoubleValue( ). Because all numeric classes, such asIntegerand
Double, are subclasses ofNumber, andNumberdefines thedoubleValue( )method, this
method is available to all numeric wrapper classes. The trouble is that the compiler has no
way to know that you are intending to createStatsobjects using only numeric types. Thus,
when you try to compileStats, an error is reported that indicates that thedoubleValue( )
method is unknown. To solve this problem, you need some way to tell the compiler that
you intend to pass only numeric types toT. Furthermore, you need some way toensurethat
onlynumeric types are actually passed.
To handle such situations, Java providesbounded types.When specifying a type parameter,
you can create an upper bound that declares the superclass from which all type arguments
must be derived. This is accomplished through the use of anextendsclause when specifying
the type parameter, as shown here:


<Textendssuperclass>

This specifies thatTcan only be replaced bysuperclass,or subclasses ofsuperclass.Thus,
superclassdefines an inclusive, upper limit.
You can use an upper bound to fix theStatsclass shown earlier by specifyingNumber
as an upper bound, as shown here:


// In this version of Stats, the type argument for
// T must be either Number, or a class derived
// from Number.
class Stats {
T[] nums; // array of Number or subclass


// Pass the constructor a reference to
// an array of type Number or subclass.
Stats(T[] o) {
nums = o;
}

// Return type double in all cases.
double average() {
double sum = 0.0;

for(int i=0; i < nums.length; i++)
sum += nums[i].doubleValue();

return sum / nums.length;
}
}


Chapter 14: Generics 325

Free download pdf