1 public class GenericTest {
2
3 public static void main(String[] args) {
4
5 Box<Number> name = new Box<Number>(99);
6 Box<Integer> age = new Box<Integer>(712);
7
8 getData(name);
9
10 //The method getData(Box<Number>) in the type GenericTest is
11 //not applicable for the arguments (Box<Integer>)
12 getData(age); // 1
13
14 }
15
16 public static void getData(Box<Number> data){
17 System.out.println("data :" + data.getData());
18 }
19
20 }
我们发现,在代码//1处出现了错误提示信息:The method getData(Box<Number>) in the t ype GenericTest is not applicable for the arguments (Box<Integer>)。显然,通过提示信息,我们知道Box<Number>在逻辑上不能视为Box<Integer>的父类。那么,原因何在呢?
1 public class GenericTest {
2
3 public static void main(String[] args) {
4
5 Box<Integer> a = new Box<Integer>(712);
6 Box<Number> b = a; // 1
7 Box<Float> f = new Box<Float>(3.14f);
8 b.setData(f); // 2
9
10 }
11
12 public static void getData(Box<Number> data) {
13 System.out.println("data :" + data.getData());
14 }
15
16 }
17
18 class Box<T> {
19
20 private T data;
21
22 public Box() {
23
24 }
25
26 public Box(T data) {
27 setData(data);
28 }
29
30 public T getData() {
31 return data;
32 }
33
34 public void setData(T data) {
35 this.data = data;
36 }
37
38 }