Archives: Generics

Java – Generic Class Example

[code lang=”java”]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());
}
}[/code]
Result:

Integer Value :10
String Value :Hello World