-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathGenDemo.java
More file actions
57 lines (45 loc) · 1.35 KB
/
GenDemo.java
File metadata and controls
57 lines (45 loc) · 1.35 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
package chapter14;
//A simple Generic Class
//Here , T is a type parameter that
//will be replaced by a real type
//when an object of type Gen is created
class Gen<T> {
T ob; //declare an object of type T
//Pass the constructor a reference to
//an object of type T
Gen(T o) {
ob = o;
}
//Return ob
T getOb() {
return ob;
}
//Show type of T
void showType() {
System.out.println("Type of T is " + ob.getClass().getName());
}
}
//Demonstrate the generic class
public class GenDemo {
public static void main(String[] args) {
Gen<Integer> iOb;
//Create a Gen<Integer> object and assign its
//reference to iOb. Notice the use of autoboxing
//to encapsulate the value 88 within an Integer object
iOb = new Gen<Integer>(88);
//Show the type of data used by iOb
iOb.showType();
//Get the value in iOb
int v = iOb.getOb();
System.out.println("value : " + v);
System.out.println();
//Create a Gen object for Strings
Gen<String> strOb = new Gen<String>("Generic Test");
//Show the type of data used b strOb
strOb.showType();
//Get the value of strOb, notice
//that cast is not needed.
String str = strOb.getOb();
System.out.println("value : " + str);
}
}