forked from tugul/CoreJava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenericClass.java
More file actions
60 lines (49 loc) · 1.77 KB
/
Copy pathGenericClass.java
File metadata and controls
60 lines (49 loc) · 1.77 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
package generics;
/**
* Generic class provides type safety and re-usability
*
* T - placeholder, any letter or letters declared in angle bracket are generic types
* The letters representing types must match literally when used! (regardless of inherited types)
*
* Limitations on generic types:
* - can't instantiate object with generic type: new T()
* - can't instantiate arrays with generic type: new T[]
* - can't call instanceof: obj instanceof T
* - can't use primitive as generic type, instead use their wrapper classes
* - can't create STATIC variable with generic type
* - can't create STATIC method with generic type defined in generic class definition
*/
class GeneralWithTwo <T, e> {
T t;
e e;
}
class AnotherGeneral <A, b,C, d extends C> {
A[] a;
b b;
C c;
}
public class GenericClass<T> {
private T tag;
public static T t; // DOES NOT COMPILE, generic type can't be used in static context
public static void method1(T t) {} // DOES NOT COMPILE
public static void method3() {
T t; // DOES NOT COMPILE
}
public void methodNonStatic(T t) {} // COMPILES
public GenericClass(T tag){
this.tag = tag;
boolean isIt = tag instanceof T; // DOES NOT COMPILE
T[] aa = new T[10]; // DOES NOT COMPILE
T t = new T(); // DOES NOT COMPILE
}
public T getTag(){
return tag;
}
public static void main(String[] args) {
GenericClass<Integer> gcI = new GenericClass<>(100);
System.out.println(gcI.getTag()); // 100
GenericClass<String> gcS = new GenericClass<>("General");
System.out.println(gcS.getTag()); // General
Integer i = gcS.getTag(); // DOES NOT COMPILE, type safety works!
}
}