-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenericFooExample.java
More file actions
105 lines (83 loc) · 2.12 KB
/
GenericFooExample.java
File metadata and controls
105 lines (83 loc) · 2.12 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package example.GenericExample;
import java.util.List;
/**
* Reference:
* - http://puremonkey2010.blogspot.com/2010/12/gossip-in-java-generics.html
*/
public class GenericFooExample {
public static void main(String[] args) {
GenericFoo<String> genericFoo = new GenericFoo<>();
genericFoo.setFoo("Hello");
System.out.println(genericFoo.getFoo());
//! Unresolved compilation problem.
// GenericFoo<String> genericFoo2 = new GenericFoo();
// genericFoo2.setFoo(123);
// System.out.println(genericFoo2.getFoo());
SubGenericQoo<String, String, Integer> subGenericQoo = new SubGenericQoo<>();
subGenericQoo.setQoo1("1");
subGenericQoo.setQoo2("George");
subGenericQoo.setQoo3(22);
System.out.println("ID: " + subGenericQoo.getQoo1() + "; Name: " + subGenericQoo.getQoo2() + "; Age: " + subGenericQoo.getQoo3());
}
}
class GenericFoo<T> {
private T foo;
public void setFoo(T foo) {
this.foo = foo;
}
public T getFoo() {
return foo;
}
}
/**
* 可利用GenericFoo的泛型功能寫一個包裝類別 (Wrapper)
*/
class WrapperFoo<T> {
private GenericFoo<T> foo;
public void setFoo(GenericFoo<T> foo) {
this.foo = foo;
}
public GenericFoo<T> getFoo() {
return foo;
}
}
/**
* 可限制泛型可用類型
*/
class ListGenericFoo<T extends List<T>> {
private T[] fooArray;
public void setFoo(T[] fooArray) {
this.fooArray = fooArray;
}
public T[] getFoo() {
return fooArray;
}
}
/**
* 擴充泛型類別、實作泛型介面
*/
class GenericQoo<T1, T2> {
private T1 qoo1;
private T2 qoo2;
public void setQoo1(T1 qoo1) {
this.qoo1 = qoo1;
}
public T1 getQoo1() {
return qoo1;
}
public void setQoo2(T2 qoo2) {
this.qoo2 = qoo2;
}
public T2 getQoo2() {
return qoo2;
}
}
class SubGenericQoo<T1, T2, T3> extends GenericQoo<T1, T2> {
private T3 qoo3;
public void setQoo3(T3 qoo3) {
this.qoo3 = qoo3;
}
public T3 getQoo3() {
return qoo3;
}
}