Generic classes and methods
What you will learn
Generics let a class, interface or method describe the type of data it handles without committing to one concrete type. A Box<String> stores text and a Box<Integer> stores an integer wrapper; the compiler checks both without requiring a manual cast at retrieval.
- Declare and instantiate a generic class and interface.
- Write a generic method and explain inference and type safety.
Use a fresh directory per example. Save as Main.java, compile with javac --release 21 Main.java, then run java Main. Only JDK standard-library dependencies are needed. List, Map and Set operations used here are brief previews of later collection chapters.
Store two different types safely
public class Main { static final class Box<T> { private final T value; Box(T value) { this.value = value; } T get() { return value; } } public static void main(String[] args) { Box<String> text = new Box<>("Map"); Box<Integer> count = new Box<>(3); System.out.println(text.get().length()); System.out.println(count.get() + 1); }}Expected output:
34The compiler knows the result types. Integer is unboxed for addition.
Rules and mental model
A type parameter such as T is a placeholder for a reference type. A type argument such as String supplies that type at a use site. The diamond <> allows the compiler to infer constructor type arguments from context. Generic methods introduce their own parameters before the return type; a static method cannot use the enclosing class’s instance type parameter unless it declares an independent one. Primitive types cannot serve as type arguments, so use wrappers such as Integer (boxing converts an int into a wrapper). A generic interface can make a repository contract reusable. A List<T> is an ordered collection of T elements; here it is a preview of Chapter 18, using only construction, add and get. Type safety does not validate business rules or forbid null by itself.
Implement a generic repository contract and generic method
public class Main { interface Repository<T> { T find(); } record Single<T>(T value) implements Repository<T> { public T find() { return value; } } static <T> T read(Repository<T> repository) { return repository.find(); } public static void main(String[] args) { Repository<String> names = new Single<>("Atlas"); Repository<Integer> quantities = new Single<>(7); System.out.println(read(names)); System.out.println(Main.<Integer>read(quantities)); }}Expected output:
Atlas7The method infers T in the first call; the explicit type witness in the second call demonstrates equivalent syntax.
Common mistakes
Do not replace a generic container with Object and cast every result. Do not use Box<int>. Choose meaningful parameter names if multiple types are involved.
Practice
Implement a generic record Pair<A,B> and a static generic method first(Pair<A,B>) that returns A. Test Pair<String,Integer>("A", 2) and Pair<Integer,String>(4, "B"). Print both first components.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Generic classes and methods — knowledge check
Apply the chapter contracts and reason about Java 21-compatible examples.
Which is a legal type argument for Box?
What does the diamond in new Box<>("Map") do?
Can a static method use the enclosing class T directly?