Calling a generic static factory method lets the compiler infer the type parameter from the argument passed in, without writing the type explicitly at the call site.
class Box<T> {
final T value;
Box(T value) { this.value = value; }
static <T> Box<T> of(T value) {
return new Box<>(value);
}
}
Box<String> boxed = Box.of("hello");
Box<Integer> num = Box.of(42);
System.out.println("boxed.value = " + boxed.value);
System.out.println("num.value = " + num.value);
boxed.value = hello
num.value = 42
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-09-27