Generic class
- Java course
- Intermediate
- Lesson 82/116
- 5 min
Learn to define generic classes with <T>.
Generic class
A generic class is a template declared with a type parameter. Writing class Box<T> { T value; } makes T a type parameter; you supply a concrete type when you use it: Box<String> b = new Box<>();.
The same class then works for String, Integer and other types in a type-safe way. No cast is needed and ClassCastException risk drops. By convention type parameters are single letters: T (type), E (element), K/V (key/value).
Using a generic class
To use a generic class with a concrete type, write Box<String> b = new Box<>();. The right side <> can stay empty; the compiler infers the type from the left side (diamond operator).
Field assignment looks like b.value = "Hello";. When you write String s = b.value; no cast is needed; the compiler knows value is a String. Giving a different type is a compile error; this is the main strength of generics.
Practice Define the Box<T> class
Define class Box<T> with a T value; field inside. In main, create a box with Box<String> b = new Box<>();, assign b.value = "Book"; and print it with System.out.println(b.value);.
Starter code
// Define the Box<T> generic class
// main: create a Box<String> instance, assign and printSample solution
class Box<T> {
T value;
}
public class Main {
public static void main(String[] args) {
Box<String> b = new Box<>();
b.value = "Book";
System.out.println(b.value);
}
}Expected output
Book
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does Box<String> specify?
- That an array is defined
- That Box is final
- That String is a subclass
- That T becomes String Correct answer
Explanation: The type inside < > is the concrete type for T.
2 Complete the generic class declaration
class Box____ {
T value;
}
class Box<T> {
T value;
}
Explanation: <T> gives the Box class a type parameter.
3 Match the generic class concepts
| Term | Meaning |
|---|---|
<T> |
Type parameter declaration |
Box<String> |
Concrete type usage |
<> |
Diamond operator |
T value |
Generic field |