Generics are a facility of generic programming that were added to the Java programming language in 2004 within version J2SE 5.0.
Generics allows parameterized type to use with method, class and interface.
This example code shows how to create and use Generic Class in Java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
public class Box { private T t; public void add(T t) { this.t = t; } public T get() { return t; } public static void main(String[] args) { Box integerBox = new Box(); Box stringBox = new Box(); integerBox.add(new Integer(10)); stringBox.add(new String("Hello World")); System.out.printf("Integer Value :%d\n\n", integerBox.get()); System.out.printf("String Value :%s\n", stringBox.get()); } } |
Output:
Integer Value :10
String Value :Hello World
String Value :Hello World