-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGenerics.java
More file actions
86 lines (70 loc) · 1.97 KB
/
Generics.java
File metadata and controls
86 lines (70 loc) · 1.97 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
package generics;
/*
* in java, generic are introduced in version 1.5
* generic provide type safety to classes as well as methods.
* we can make a class or method generic with a generic data type which later can be changed to
* any supported data type as per requirement.
* hence providing the facility of code reusing too.
* generic does not support fundamental data types and only works with objects
* hence in case fundamental data types required to be used
* we can use corresponding wrapper class object.
*/
public class Generics {
int val;
float fl;
// generic constructor in a non generic class
<V extends Integer, S extends Float> Generics(V v, S s) {
val = v;
fl = s;
System.out.println(val + " " + fl);
}
public static void main(String[] args) {
// generic object initialization
GenClass<Integer> obj1 = new GenClass<>(5, 6);
System.out.println(obj1.getOb() + " " + obj1.getX());
GenClass<String> obj2 = new GenClass<>("HELLO WORLD", 6);
System.out.println(obj2.getOb() + " " + obj1.getX());
GenClass<Character> obj3 = new GenClass<>('c', 6);
System.out.println(obj3.getOb() + " " + obj1.getX());
GenericClass<Integer, String> obj4 = new GenericClass<>(5, "hello");
System.out.println(obj4.getTob());
System.out.println(obj4.getUob());
System.out.println(add(5, 5));
Generics gs = new Generics(195, 220f);
}
// generic method in a non generic class
public static <T extends Integer> int add(T t, T u) {
int sum = t.intValue() + u.intValue();
return sum;
}
}
// generic class example
class GenClass<T> {
public T ob;
private int x;
GenClass(T ob, int x) {
this.ob = ob;
this.x = x;
}
public T getOb() {
return ob;
}
public int getX() {
return x;
}
}
// generic class with multiple parameter example
class GenericClass<T, U> {
public T tob;
public U uob;
public GenericClass(T tob, U uob) {
this.tob = tob;
this.uob = uob;
}
public T getTob() {
return tob;
}
public U getUob() {
return uob;
}
}