ProLesson 6.2Intermediate2 min readUpdated 30 October 2026
Generic classes and methods
Write your own generic classes, interfaces and methods, so one piece of code works safely with any type.
Using generic types is easy. Writing your own is the next step, and it's how libraries like the Collections Framework are built.
01A generic class
Add a type parameter in angle brackets after the class name, then use it like a type:
GenericBox.java
class Box<T> {
private final T value;
Box(T value) {
this.value = value;
}
T get() {
return value;
}
boolean isPresent() {
return value != null;
}
}
public class GenericBox {
public static void main(String[] args) {
Box<String> name = new Box<>("Asha");
Box<Integer> age = new Box<>(28);
String n = name.get(); // no cast
int a = age.get();
System.out.println(n + " is " + a);
System.out.println(new Box<String>(null).isPresent());
}
}Asha is 28 false
T is a placeholder. When you write Box<String>, every T inside means String for that object.
Loading the rest of the lesson…