-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExample123.java
More file actions
31 lines (24 loc) · 824 Bytes
/
Example123.java
File metadata and controls
31 lines (24 loc) · 824 Bytes
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
// Example 123 from page 93
//
class Hold<T> {
private T contents;
@SuppressWarnings("unchecked")
public void set(Object x) {
contents = (T)x; // Unchecked cast
}
public T get() {
return contents;
}
}
class Example123 {
public static void main(String[] args) {
Hold<Integer> h = new Hold<Integer>();
h.set("foo"); // Succeeds at run-time
System.out.println("Succesfully executed h.set(\"foo\")");
h.get(); // Succeeds at run-time
System.out.println("Succesfully executed h.get()");
// String s = h.get(); // Illegal, rejected by compiler
Integer i = h.get(); // Legal, but fails at run-time
System.out.println("Succesfully executed Integer i = h.get()");
}
}