-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathGenericClassAndMethodExample.java
More file actions
45 lines (36 loc) · 1.15 KB
/
GenericClassAndMethodExample.java
File metadata and controls
45 lines (36 loc) · 1.15 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
package Generics;
// A generic class
class Box<T> {
private T content;
public void setContent(T content) {
this.content = content;
}
public T getContent() {
return content;
}
}
public class GenericClassAndMethodExample {
// A generic method
public static <E> void printArray(E[] inputArray) {
for (E element : inputArray) {
System.out.printf("%s ", element);
}
System.out.println();
}
public static void main(String[] args) {
// Using the generic class
Box<Integer> integerBox = new Box<>();
integerBox.setContent(10);
System.out.println("Integer Box content: " + integerBox.getContent());
Box<String> stringBox = new Box<>();
stringBox.setContent("Hello Generics");
System.out.println("String Box content: " + stringBox.getContent());
// Using the generic method
Integer[] intArray = {1, 2, 3, 4, 5};
String[] stringArray = {"A", "B", "C"};
System.out.print("Integer Array: ");
printArray(intArray);
System.out.print("String Array: ");
printArray(stringArray);
}
}