Declaring a Generic Class with a Single Type Parameter
What you'll learn: How to create a class that can work with any type by declaring a type parameter using <T> syntax.
The Core Idea
A generic class is like a template that can hold or operate on different types without knowing in advance what those types will be. Instead of hardcoding String or Integer, you declare a placeholder (called a type parameter) that will be filled in later when someone uses your class.
The syntax is simple: add <T> after your class name, where T is a placeholder name (by convention, single uppercase letters like T, E, or K are used). You can then use T throughout your class body wherever you'd normally use a concrete type.
Plain-English Analogy
Think of a generic class as a box with a label that says "Contents: _____". You don't fill in the blank when you design the box—you let whoever uses the box decide whether it holds books, tools, or toys.
Syntax Example
public class Box<T> {
private T contents;
public void store(T item) {
this.contents = item;
}
public T retrieve() {
return contents;
}
}
Here, <T> declares the type parameter, and T is used as the type for the field, method parameter, and return type. When someone creates a Box<String>, every T becomes String. If they create Box<Integer>, every T becomes Integer.
Why This Matters
Without generics, you'd need separate StringBox, IntegerBox, etc., or use Object everywhere and lose type safety. Generics let you write one class that works safely with any type.
Key Takeaway:
Declare a generic class with class ClassName<T> and use T as a type placeholder throughout the class body—users will specify the actual type when they instantiate your class.