-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenericsBounded.java
More file actions
41 lines (37 loc) · 1.26 KB
/
Copy pathGenericsBounded.java
File metadata and controls
41 lines (37 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// 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;
}
// Return the reciprocal.
double reciprocal() {
return 1 / num.doubleValue();
}
// Return the fractional component.
double fraction() {
return num.doubleValue() - num.intValue();
}
}
public class GenericsBounded {
public static void main(String[] args) {
NumericFns<Integer> iOb =
new NumericFns<Integer>(5);
System.out.println("Reciprocal of iOb is " +
iOb.reciprocal());
System.out.println("Fractional component of iOb is " +
iOb.fraction());
System.out.println();
NumericFns<Double> dOb =
new NumericFns<Double>(5.25);
System.out.println("Reciprocal of dOb is " +
dOb.reciprocal());
System.out.println("Fractional component of dOb is " +
dOb.fraction());
// This won't compile because String is not a
// subclass of Number.
// NumericFns<String> strOb = new NumericFns<String>("Error");
}
}