Generic classes: type parameters and conventions
Defining your own generic class, multiple type params, and the naming conventions.
Defining a generic class
You introduce a type parameter after the class name. Inside the class body you use the parameter exactly like a type:
public class Box<T> {
private T value;
public Box(T value) { this.value = value; }
public T get() { return value; }
public void set(T value) { this.value = value; }
}
Box<String> sb = new Box<>("hello");
Box<Integer> ib = new Box<>(42);
String s = sb.get(); // no cast
You can have multiple type parameters — the most important example is Map<K, V>:
public class Pair<K, V> {
private final K first;
private final V second;
public Pair(K first, V second) {
this.first = first;
this.second = second;
}
public K getFirst() { return first; }
public V getSecond() { return second; }
}
Pair<String, Integer> entry = new Pair<>("score", 98);
Conventional single-letter names:
| Letter | Meaning |
|---|---|
| T | Type (generic) |
| E | Element (collections) |
| K | Key |
| V | Value |
| N | Number |
These are conventions, not requirements — but they are universally recognised and expected on the OCP exam and in production code.