-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenericMethods.java
More file actions
87 lines (73 loc) · 1.86 KB
/
GenericMethods.java
File metadata and controls
87 lines (73 loc) · 1.86 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
package generic;
class Apple{
Apple(){
System.out.println("I'm Apple");
}
}
class Banana extends Apple{
Banana(){
System.out.println("I'm Banana extended from Apple");
}
}
class Mango extends Banana{
Mango(){
System.out.println("I'm Mango extended from Banana");
}
}
class ClassG<T>{
T[] A = (T[]) new Object[10];
int length = 0;
void append(T Value){
A[length++] = Value;
}
void display(){
for(int i=0; i<length; i++){
System.out.print(A[i]+" ");
}
}
}
public class GenericMethod {
// Generic method
static <E> void show(E[] list) {
for (E x : list) {
System.out.println(x);
}
// Bound type works here
/* static <E extends Integer> void show(E... list){
for(E x: list){
System.out.println(x);
}
*/
}
// WildCard<?> Unbounded
static void fun1(ClassG<?> P){
P.display();
}
// WildCard<?> bounded with extends i.e, Upper Bound
static void fun2(ClassG<? extends Apple> P){
P.display();
}
// WildCard<?> bounded with super i.e, Lower Bound
static void fun3(ClassG<? super Mango> P){
P.display();
}
public static void main(String[] args) {
show(new String[]{"Java", "Machine Learning"});
show(new Integer[]{12,34});
ClassG<String> S = new ClassG<>();
S.append("Java");
S.append("ML");
ClassG<Integer> I = new ClassG<>();
I.append(45);
I.append(73);
fun1(S);
fun1(I);
ClassG<Apple> A = new ClassG<>();
ClassG<Banana> B = new ClassG<>();
ClassG<Mango> C = new ClassG<>();
A.append(new Mango());
fun2(A);
fun2(B);
fun3(C);
}
}