Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces, and methods, providing stronger type checks at compile time and eliminating the need for casting.
Source Code
public class Box {
private T t;
public void set(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.set(new Integer(10));
stringBox.set(new String("Hello World"));
System.out.printf("Integer Value :%dnn", integerBox.get());
System.out.printf("String Value :%sn", stringBox.get());
}
}