Advanced level · Module 1: Generics, Lambdas and Streams · Lesson 1 of 4
Generic Classes and Methods
Write classes and methods that work with any type while keeping compile-time type safety.
In this lesson you will
- Write generic classes and methods with type parameters
- Use bounded type parameters and wildcards appropriately
Key concepts
type parameter <T>bounded type <T extends Comparable<T>>wildcards ? extends / ? supertype erasure
The lesson
Generics let one class work with many types safely. class Box<T> { private T value; … } can hold a String or an Invoice, and the compiler checks that you never take a String out of a Box<Invoice>. Without generics you would use Object and cast, moving errors from compile time to run time.
A generic method declares its own type parameter: static <T> T firstOrDefault(List<T> list, T fallback). Bounds restrict the types allowed: <T extends Comparable<T>> T max(List<T> items) works with any type that can be compared.
Wildcards make APIs flexible: a method that reads numbers can accept List<? extends Number>, and one that adds integers can accept List<? super Integer>. Generic types are erased at run time, so you cannot write new T() or check instanceof List<String>.
Step by step
- Write a generic Pair<A, B> class with getters.
- Write a generic method max for any Comparable type.
- Write sumAll(List<? extends Number>) and call it with integers and doubles.
- Try new T() and read the compiler error.
Practice activity
Write a generic Result<T> class that holds either a value or an error message, and use it as the return type of a parsing method.
Expected result: Callers receive Result<Integer> or Result<LocalDate> and must check for an error before using the value.
Check your understanding
-
Why are generics safer than using Object?
Show answer
Type errors are caught at compile time and no casts are needed.
-
What does <T extends Comparable<T>> allow?
Show answer
Only types that can be compared with themselves, so the method can call compareTo.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.