-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenericMethods.java
More file actions
44 lines (35 loc) · 977 Bytes
/
GenericMethods.java
File metadata and controls
44 lines (35 loc) · 977 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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/*
* we can add any type of Type Parameter <> by using the notation <?>
*
* for Eg:
* */
/*
class ArrayListClass<T> {
public static void main(String[] args) {
ArrayList<?> strAl = new ArrayList<>();
ArrayListClass obj = new ArrayListClass();
obj.add(strAl, "Hello");
obj.add(strAl, 12.45);
}
public void add(ArrayList<?> arrList, T element) {
arrList.add(element);
}
}
the above code is incorect because we cannot use<?> for declaration purpose. A generic class needs to know
the type of parameter passed at compile time. This is best suitable for Read-Only operations.
*/
abstract class Calculator<T extends Number> {
abstract void add(T a, T b);
abstract void sub(T a, T b);
abstract void mul(T a, T b);
abstract void div(T a, T b);
}
class Printer <T> {
private T somethingToPrint;
public Printer(T somethingToPrint) {
this.somethingToPrint = somethingToPrint;
}
public void print() {
System.out.println(this.somethingToPrint);
}
}