Java Generics: Generic Classes, Interfaces, Methods and Type Erasure (OCP 21)
Generics for the OCP 21 exam: declaring generic classes, interfaces and records, type parameter naming, type erasure and its limits, overloading and overriding with generic types, generic methods and explicit type arguments, shadowed type parameters, and bounded type parameters.
kvi5hnuCode Sprout team member9 min readOn this page
You've been using generics since the first List<String>. This article is about writing them: your own generic classes, interfaces, records and methods, and the rules that follow from how Java implements generics, which is through type erasure.
Generic classes
A class declares type parameters in angle brackets after its name. Inside the class, the parameter can be used almost anywhere a type can:
public class Locker<T> {
private T item;
public void store(T item) { this.item = item; }
public T retrieve() { return item; }
}
Locker<String> keys = new Locker<>(); // T is String for this object
keys.store("brass key");
String k = keys.retrieve(); // no cast needed
keys.store(42); // DOES NOT COMPILE: int isn't a String
The class knows nothing about the objects it holds, and those objects don't need to know about the class. That's the point. Before Java 5, the same class would have used Object, and every caller would have had to cast the result, risking a ClassCastException.
A class can have several type parameters, separated by commas: class Labelled<K, V>. When you use the class, you must supply the right number of type arguments. Labelled<String> doesn't compile when two are declared.
Naming convention: a single uppercase letter, so it can't be mistaken for a real class:
Efor a collection elementKandVfor a map key and valueNfor a numberTfor a general typeS,U,Vand so on for additional types
Nothing stops you from naming a type parameter String or B, though, and the exam uses this to confuse you (see "shadowing" below).
Type arguments must be reference types. Locker<int> doesn't compile; use Locker<Integer>, and autoboxing does the rest.
The diamond and raw types
new Locker<>()lets the compiler infer the type argument from the target.Locker<> x;as a declaration doesn't compile, because the diamond is only fornew.- Using a generic type without type arguments (
Locker x = new Locker();) makes it a raw type. Raw types still compile, for compatibility with pre-Java 5 code. All generic checking is turned off for them. javac prints an "unchecked or unsafe operations" note when you use them unsafely, and-Xlint:rawtypes,unchecked(or an IDE) shows the individual warnings. On the exam, a rawListholdsObjects and accepts anything.
Generic interfaces
An interface can be generic too. A class implementing it has three options:
interface Converter<T> {
String convert(T input);
}
class CelsiusConverter implements Converter<Double> { // 1. choose the type
public String convert(Double c) { ... }
}
class BracketConverter<U> implements Converter<U> { // 2. stay generic, pass the choice on
public String convert(U input) { ... }
}
class OldConverter implements Converter { // 3. raw type: the parameter is Object
public String convert(Object o) { ... } // compiles (raw type; -Xlint:rawtypes flags it)
}
A mismatch is a common trap: implements Converter<Double> with a method convert(Object o) doesn't compile. It doesn't override convert(Double), and the two methods clash after erasure.
Generic records
Records can declare type parameters, and they work just like classes:
record Range<T extends Comparable<T>>(T low, T high) {
Range {
if (low.compareTo(high) > 0) throw new IllegalArgumentException();
}
}
Range<Integer> teen = new Range<>(13, 19);
Since Java 21, record patterns also work with generic records, and they can infer the type arguments, so if (obj instanceof Range(var lo, var hi)) compiles without writing <...>.
Type erasure

Generics are a compile-time feature. After checking your code, the compiler erases the type parameters:
- Each type parameter is replaced by its bound:
Objectwhen there isn't one, or the first bound, such asNumberfor<N extends Number>. - Type arguments disappear from types.
List<String>becomesList. - Casts are inserted where your code reads a generic value:
String k = (String) keys.retrieve();.
So there's just one Locker.class. Locker<String> and Locker<Integer> are the same class at run time, and keys.getClass() == coins.getClass() is true. Erasure kept generic code compatible with the older, non-generic libraries and JVMs.
What erasure rules out
Because the type argument doesn't exist at run time, a type parameter T can't be used where Java would need to know the real type:
| Not allowed | Why |
|---|---|
new T() | the erased call would be new Object() |
new T[10] (generic array creation) | the array's real type would be Object[] |
obj instanceof T, obj instanceof List<String> | the run-time check can't see type arguments (instanceof List<?> is fine) |
static T field, T in a static method of the generic class | type parameters belong to an instance |
catch (T e) | the catch needs a concrete class |
primitive type arguments: List<int> | erasure needs a reference type |
A static method can still be generic if it declares its own type parameter, as shown below. Since Java 16, instanceof with type arguments is allowed when it's safe from the static type, such as List<String> l; l instanceof ArrayList<String> a, but the exam focuses on the classic rule.
Overloading and overriding after erasure
Two methods whose signatures become identical after erasure clash:
void store(List<String> words) { }
void store(List<Integer> nums) { } // DOES NOT COMPILE: both erase to store(List)
The same goes for a subclass that "overloads" a parent method with a different type argument:
class Shelf { void load(List<Object> items) { } }
class SmallShelf extends Shelf {
void load(List<Object> items) { } // fine: overrides
void load(ArrayList<Double> items) { } // fine: overloads (ArrayList ≠ List)
void load(List<Double> items) { } // DOES NOT COMPILE: same erasure, doesn't override
}
For return types, overriding allows a covariant class (ArrayList<CharSequence> for List<CharSequence>), but the type argument must match exactly:
class Reader { List<CharSequence> lines() { ... } CharSequence title() { ... } }
class FastReader extends Reader {
ArrayList<CharSequence> lines() { ... } // fine: ArrayList is a List
String title() { ... } // fine: plain covariant return
}
class BadReader extends Reader {
List<String> lines() { ... } // DOES NOT COMPILE: List<String> isn't a List<CharSequence>
}
To check an exam question: erase the generics, work out which methods override and which overload, then make sure the type arguments of the overriding methods match.
Generic methods
A method can declare its own type parameters. They go in angle brackets immediately before the return type:
static <T> List<T> repeat(T value, int times) { ... }
static <T, R> List<R> mapAll(List<T> src, Function<T, R> f) { ... }
public <T> void log(T t) { ... } // instance methods can be generic too
static T broken(T t) { return t; } // DOES NOT COMPILE: T was never declared
static void <T> wrong(T t) { } // DOES NOT COMPILE: <T> must come before the return type
This is how static methods get generic types: a static method can't use the class's T, but it can declare its own, as in static <U> Locker<U> of(U u).
The compiler usually infers the type argument from the arguments and the target. You can also state it explicitly, with the type before the method name and after the dot:
List<Character> zs = Solution.<Character>repeat('z', 2);
this.<Integer>log(5);
<String>log("x"); // DOES NOT COMPILE: an explicit type argument needs a receiver before the dot
If inference can't satisfy everything, it fails. For example, List<String> l = repeat2("a", 1) doesn't compile when repeat2 is declared as <T> List<T> repeat2(T a, T b), because T would have to be both String and Integer. Without the List<String> target, T is inferred as a common supertype, and the call compiles.
Shadowing: the same name at two levels
A method's type parameter is independent of the class's, even when both have the same name:
class Tricky<T> {
<T> T echo(T t) { return t; } // this T hides the class's T
}
Tricky<Integer> tricky = new Tricky<>();
String s = tricky.echo("not an Integer"); // compiles: the method's T is String
The exam can be even sneakier, using a class name as a type parameter name: <B extends A> B make() { return new B(); }. Inside that method, B is a type parameter, not the class B, so new B() doesn't compile.
Bounded type parameters
An unbounded T only offers Object's methods. A bound restricts the allowed type arguments and, in return, unlocks the bound's methods:
static <N extends Number> double twice(N n) { return n.doubleValue() * 2; }
twice(3); // fine: Integer is a Number
twice("3"); // DOES NOT COMPILE
static <T extends Comparable<T>> T max(T a, T b) { return a.compareTo(b) >= 0 ? a : b; }
max("pear", "fig"); // pear
- The keyword is always
extends, even for an interface bound.<T implements Comparable<T>>doesn't compile. - For multiple bounds, use
&. At most one bound can be a class, and it must come first:<N extends Number & Comparable<N>>compiles, but<N extends Comparable<N> & Number>doesn't ("interface expected here"). - A type parameter erases to its first bound.
- Classes and records can be bounded too:
class Stats<N extends Number>,record Range<T extends Comparable<T>>.
Wildcards (?, ? extends, ? super) are a different tool for a different job. They're covered in the next article.
What's current
- Nothing in this article changed in Java 22 through 25, so the rules apply to both the Java 21 exam (1Z0-830) and the Java 25 exam (1Z0-831).
- Generic types are still erased at run time. Project Valhalla's plans for specialized generics aren't part of any release through Java 25.
Exam traps from this article
A complete example
The program declares a generic class, a two-parameter class, a generic interface with two implementations, and a bounded generic record that validates itself. It adds generic methods with inferred and explicit type arguments and a method with two bounds. Finally it shows a shadowed type parameter and the run-time effect of erasure.
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
public class Solution {
// A generic class: T is chosen by whoever creates a Locker
static class Locker<T> {
private T item;
void store(T item) { this.item = item; }
T retrieve() { return item; }
boolean isEmpty() { return item == null; }
}
// Two type parameters
static class Labelled<K, V> {
private final K label;
private final V value;
Labelled(K label, V value) { this.label = label; this.value = value; }
@Override public String toString() { return label + " -> " + value; }
}
// A generic interface and two ways to implement it
interface Converter<T> {
String convert(T input);
}
static class CelsiusConverter implements Converter<Double> { // fixes T = Double
public String convert(Double c) { return c + "C = " + (c * 9 / 5 + 32) + "F"; }
}
static class BracketConverter<U> implements Converter<U> { // passes the choice on
public String convert(U input) { return "[" + input + "]"; }
}
// A generic record with a compact constructor
record Range<T extends Comparable<T>>(T low, T high) {
Range {
if (low.compareTo(high) > 0) throw new IllegalArgumentException(low + " > " + high);
}
boolean contains(T value) { return low.compareTo(value) <= 0 && value.compareTo(high) <= 0; }
}
// Generic methods: the type parameter list goes right before the return type
static <T> List<T> repeat(T value, int times) {
List<T> result = new ArrayList<>();
for (int i = 0; i < times; i++) result.add(value);
return result;
}
static <T, R> List<R> mapAll(List<T> source, Function<T, R> f) {
List<R> out = new ArrayList<>();
for (T t : source) out.add(f.apply(t));
return out;
}
// A bounded type parameter with two bounds: class first, then interfaces
static <N extends Number & Comparable<N>> N largest(List<N> values) {
N best = values.getFirst();
for (N n : values) if (n.compareTo(best) > 0) best = n;
return best;
}
// A method type parameter named T hides the class's T
static class Tricky<T> {
<T> T echo(T t) { return t; }
}
public static void main(String[] args) {
Locker<String> keys = new Locker<>();
keys.store("brass key");
String k = keys.retrieve(); // no cast needed
Locker<Integer> coins = new Locker<>();
System.out.println("locker: " + k + ", coins empty? " + coins.isEmpty());
System.out.println("pair: " + new Labelled<>("altitude", 8_848));
List<Converter<Double>> converters = List.of(new CelsiusConverter(), new BracketConverter<>());
for (Converter<Double> c : converters) System.out.println("convert: " + c.convert(21.5));
Range<Integer> teen = new Range<>(13, 19);
Range<String> aToM = new Range<>("a", "m");
System.out.println("range: 15 in teen? " + teen.contains(15) + ", \"q\" in a..m? " + aToM.contains("q"));
try {
new Range<>(9.5, 2.0);
} catch (IllegalArgumentException e) {
System.out.println("range rejected: " + e.getMessage());
}
List<String> echoes = repeat("hey", 3);
List<Integer> lengths = mapAll(List.of("ox", "lynx", "heron"), String::length);
System.out.println("generic methods: " + echoes + " " + lengths);
System.out.println("explicit type argument: " + Solution.<Character>repeat('z', 2));
System.out.println("largest: " + largest(List.of(4, 17, 9)) + " " + largest(List.of(2.5, -1.0)));
Tricky<Integer> tricky = new Tricky<>();
String s = tricky.echo("not an Integer"); // method's T is String here
System.out.println("tricky: " + s);
// Type erasure: one class at run time, whatever the type argument
System.out.println("same class at run time? " + (keys.getClass() == coins.getClass())
+ " (" + keys.getClass().getSimpleName() + ")");
}
}
Output:
locker: brass key, coins empty? true
pair: altitude -> 8848
convert: 21.5C = 70.7F
convert: [21.5]
range: 15 in teen? true, "q" in a..m? false
range rejected: 9.5 > 2.0
generic methods: [hey, hey, hey] [2, 4, 5]
explicit type argument: [z, z]
largest: 17 2.5
tricky: not an Integer
same class at run time? true (Locker)
Points to notice:
keys.retrieve()returns aStringwithout a cast. The compiler inserts the cast after erasure.- One list holds both converters as
Converter<Double>.BracketConverter<>inferredU = Doublefrom the list's type. Range<T extends Comparable<T>>can callcompareToonTbecause of its bound.new Range<>(9.5, 2.0)inferredDoubleand was rejected by the compact constructor.largestworks forIntegerandDoublebecause both areNumberandComparableto themselves.Tricky<Integer>.echoaccepted aString, because the method'sThides the class's.Locker<String>andLocker<Integer>share one class at run time.
Common questions
Why didn't Java keep type arguments at run time, as C# does? Compatibility. Erasure let generic code run on existing JVMs and call existing libraries without changes. The cost is the list of limitations above. Project Valhalla is exploring better generics for primitives and value classes in future Java versions, but nothing on the Java 21 exam changes.
How do I create a T or a T[] if I need one?
Pass in a factory or a class object, such as Supplier<T> or IntFunction<T[]>. That's exactly what Collection.toArray(IntFunction<T[]>) does, as in list.toArray(String[]::new).
When should a method be generic instead of taking Object?
When the type of what goes in determines the type of what comes out, or when several parameters must share one type. If the method just reads values of any type, a wildcard (next article) is often simpler.
Summary
- Generic classes, interfaces and records declare type parameters such as
<T>or<K, V>. Users supply reference-type arguments, often with the diamond. - Type erasure replaces each type parameter with its bound (or
Object) and inserts casts, so there's only one class at run time. - Because of erasure,
new T(), generic arrays,instanceof T, static uses ofTand signatures differing only in type arguments are all illegal. - Generic methods declare
<T>before the return type. Type arguments are inferred or given explicitly asType.<X>method(). A method'sThides a class'sT. - Bounded type parameters (
<T extends Bound & Interface>) restrict type arguments and unlock the bound's methods.
Practice quiz
Test yourself with the generic classes and methods quiz: 10 exam-style questions with explanations.
Previous: Java Sequenced Collections: SequencedCollection, SequencedSet and SequencedMap (OCP 21)
Next: Java Generic Wildcards: Unbounded, Upper-Bounded and Lower-Bounded Types (OCP 21)
Related reading
- Java Packages and Imports: Wildcards, Conflicts, Compiling and the Class Path (OCP 21)
- Java Reflection and Generics: Class<T>, Type Tokens and the Type Interface
- Java Generics Inheritance Rules and Wildcards: extends, super and ?
- Java Generics: Generic Classes and Generic Methods
- Java Polymorphism: Reference Types, Casting and Virtual Method Calls (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.