Memra

Generic classes: type parameters and conventions

◈ 4 cards

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:

LetterMeaning
TType (generic)
EElement (collections)
KKey
VValue
NNumber

These are conventions, not requirements — but they are universally recognised and expected on the OCP exam and in production code.

T = StringT = Integerclass Box<T>one class bodyBox<String>get() returns StringBox<Integer>get() returns Integer
One class body, one type parameter. Each use site fixes T to a different type, and get() carries that type back out — which is why no cast is needed.
NORMAL ~/memra/learn/java-from-zero/generic-classes utf-8 LF