🎯 What you will learn
Before generics (Java 1.4), List held Object. You had to cast on retrieval, and bad casts only crashed at runtime. Generics move type errors to compile time. By the end of this lesson you will understand:
- Generic classes —
Box<T>that works for any type - Generic methods —
<T extends Comparable<T>> T max(T a, T b) - Upper bounds —
<T extends Number>to restrict T to numeric types - Multiple bounds —
<T extends A & B> - Wildcards —
? extends T,? super T,? - Type erasure — what generics become at runtime
🎓 Real-world scenario
VidyaPath runs adaptive mock exams for 40,000 students. Priya, a backend engineer, needs a reusable Box<T> container that works for any type, a Statistics utility that accepts any numeric list (Integer scores or Double percentages), and wildcard-based helpers that can print any kind of list without requiring a specific type. Without generics, she'd need casts everywhere — and cast failures only appear at runtime.
🔣 Why generics?
Before generics (Java 1.4), List held Object. You had to cast on retrieval, and bad casts only crashed at runtime. Generics move type errors to compile time: List<String> rejects a list.add(42) at compile time. The type parameter T is erased at runtime (type erasure) — the JVM sees Object — but the compiler enforces correctness before erasure.
Key idea: Type parameters are a compile-time concept. At runtime, List<String> and List<Integer> are both just List. This is type erasure — the price of backward compatibility with pre-generics Java code.
📦 Generic classes and methods
A generic class declares a type parameter in angle brackets after the class name: class Box<T>. Any use of T inside is a placeholder resolved when you instantiate the class. A generic method declares its own type parameter before the return type.
🔒 Bounded type parameters
Use <T extends Number> to restrict T to Number and its subclasses (Integer, Double, Long…). This lets you call Number methods like doubleValue() on T inside the method. Combine multiple bounds with &: <T extends Number & Comparable<T>>.
🃏 Wildcards
Wildcards (?) are for call-site flexibility. Use ? extends T (upper-bounded) when you only need to read from a collection. Use ? super T (lower-bounded) when you need to write into a collection. Use ? (unbounded) for a method that treats everything as Object.
PECS rule: Producer Extends, Consumer Super. If you read from a generic structure (it produces values for you), use ? extends T. If you write into it (it consumes values you provide), use ? super T.
Quick reference — generics cheat sheet
| Syntax | Meaning |
|---|---|
Box<T> | Generic class, T is any type |
<T extends Number> | Upper bound: T must be Number or subclass |
<T extends A & B> | Multiple bounds: T must implement both |
List<? extends Number> | Upper-bounded wildcard: read-only, any Number subtype |
List<? super Integer> | Lower-bounded wildcard: can add Integers |
List<?> | Unbounded wildcard: any type, read-only as Object |
⚠️ Common mistakes
new T() inside a generic class. The compiler doesn't know T's constructor at compile time. Work around with a Supplier<T> parameter or factory method.Box<int> doesn't compile. Generics only work with reference types. Use the wrapper: Box<Integer>.List<? extends Number> is a wildcard (cannot add elements). <T extends Number> void foo(List<T>) is a type parameter (can add T elements). Wildcards are for flexibility at call sites; type parameters are for methods that need a specific consistent type.List<? extends Number> list is read-only — list.add(5) is a compile error because the compiler can't guarantee the list is List<Integer> vs List<Double>.🎤 Interview Q&A
At compile time, the compiler checks generic type constraints and inserts casts where needed. At runtime, all type parameters are erased — List<String> and List<Integer> both become List (raw type) in the bytecode. This maintains backward compatibility with pre-generics code but means you can't do instanceof List<String> at runtime — only instanceof List.
Raw types bypass compiler type checking — you can add any object and only discover type mismatches at runtime via ClassCastException. Generic types catch these errors at compile time. Raw types also generate unchecked warnings and are considered deprecated style in modern Java.
PECS guides wildcard choice: if a generic structure produces (you read from it), use ? extends T. If it consumes (you write to it), use ? super T. Example: copy(List<? extends Number> src, List<? super Number> dest) — src produces Numbers, dest consumes them. If you need both read and write, use a concrete type parameter <T>.
Pass a Supplier<T> or Class<T> to the constructor: class Repo<T> { Repo(Supplier<T> factory) { T instance = factory.get(); } }. Or use a static factory method where T is known. Reflection via clazz.getDeclaredConstructor().newInstance() also works but is unsafe and verbose.
This is called generic invariance. If List<Dog> were assignable to List<Animal>, you could add a Cat to what is actually a List<Dog> at runtime — breaking type safety. Arrays are covariant (Dog[] is a subtype of Animal[]) but this leads to ArrayStoreException at runtime. Generics chose compile-time safety over covariance. Use List<? extends Animal> when you want a read-only view accepting any Animal subtype.
📝 Quiz — 5 questions
Box<int> — will this compile?<T extends Number> means T:List<? extends Number>?<T extends A & B> means T must:Next: Lambdas and Functional Interfaces →
✅ Key takeaways
- Generics move cast failures from runtime to compile time.
<T>means any type;<T extends X>restricts T to X and its subtypes.- Wildcards:
? extends Tfor reading,? super Tfor writing,?for any. - Primitives are not allowed as type parameters — use wrapper types.
- Type parameters are erased at runtime; JVM sees
Object.
From generics to production Spring Boot
Join the Best AI Programs — three 5-month courses, fully online, with placement assistance. Week 1 is free.
Explore our AI-era courses →