Core Java: A generic method infers its type parameter from the argument

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.

Code
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);
Output
boxed.value = hello
num.value = 42
Advertisement
More in JAVA

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

© Java Coding Hub · About · Contact · Privacy · Terms