Java Reference
In-Depth Information
Unfortunately, NumericFns will not compile as written because both methods will gen-
erate compile-time errors. First, examine the reciprocal( ) method, which attempts to re-
turn the reciprocal of num . To do this, it must divide 1 by the value of num . The value
of num is obtained by calling doubleValue( ) , which obtains the double version of the
numeric object stored in num . Because all numeric classes, such as Integer and Double ,
are subclasses of Number , and Number defines the doubleValue( ) 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 create NumericFns objects using only numeric types.
Thus, when you try to compile NumericFns , an error is reported that indicates that the
doubleValue( ) method is unknown. The same type of error occurs twice in fraction( ) ,
which needs to call both doubleValue( ) and intValue( ) . Both calls result in error mes-
sages stating that these methods are unknown. To solve this problem, you need some way
to tell the compiler that you intend to pass only numeric types to T . Furthermore, you need
some way to ensure that only numeric types are actually passed.
To handle such situations, Java provides bounded types . When specifying a type para-
meter, you can create an upper bound that declares the superclass from which all type ar-
guments must be derived. This is accomplished through the use of an extends clause when
specifying the type parameter, as shown here:
< T extends superclass >
This specifies that T can be replaced only by superclass , or subclasses of superclass . Thus,
superclass defines an inclusive, upper limit.
You can use an upper bound to fix the NumericFns class shown earlier by specifying
Number as an upper bound, as shown here:
Search WWH ::




Custom Search