🎯 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
💼 Interview reality: "What is type erasure?" and "Explain PECS (Producer Extends, Consumer Super)" appear in senior Java interviews. The interview Q&A at the bottom walks through both in depth.

🎓 Real-world scenario

🎓
Real-world scenario · VidyaPath
VidyaPath — Priya's type-safe exam statistics engine (Bangalore)

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.

javac GenericBox.java && java GenericBox
GenericBox.javaLesson 15 · VidyaPath generic container
verified output
=== VidyaPath — Generic Boxes === Box[studentName: Priya Sharma (String)] Box[examScore: 720 (Integer)] Box[gpa: 3.87 (Double)] Student: Priya Sharma Score: 720 Max scores: max(720, 810) = 810 max("CAT","XAT") = XAT

🔒 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>>.

javac BoundedTypes.java && java BoundedTypes
BoundedTypes.javaLesson 15 · VidyaPath exam statistics
verified output
=== VidyaPath — Exam Statistics === Scores : [580, 640, 720, 810, 755, 690] Sum : 4195 Avg : 699.2 Max : 810 Percents: [72.5, 81.0, 68.3, 90.2, 77.8] Sum : 389.8 Avg : 78.0% Max : 90.2%

🃏 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.

javac WildcardDemo.java && java WildcardDemo
WildcardDemo.javaLesson 15 · VidyaPath wildcard helpers
verified output
=== VidyaPath — Wildcard Demo === Total int scores : 1940 Total dbl scores : 243.7 Subjects : Math Physics CS Scores : 580 640 720

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

SyntaxMeaning
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

Instantiating with new T()
Due to type erasure, you can't do 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.
Using primitives as type parameters
Box<int> doesn't compile. Generics only work with reference types. Use the wrapper: Box<Integer>.
Confusing wildcard with type parameter
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.
Adding to an upper-bounded wildcard list
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

EasyWhat is type erasure in Java generics?
+

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.

EasyWhy should you use List<String> instead of a raw 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.

MediumWhat is the PECS rule (Producer Extends, Consumer Super)?
+

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>.

MediumHow do you work around the restriction that you can't do new T() inside a generic class?
+

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.

HardWhy is List<Dog> not a subtype of List<Animal> even though Dog extends Animal?
+

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

Question 1 of 5
Box<int> — will this compile?
Question 2 of 5
<T extends Number> means T:
Question 3 of 5
Can you add elements to List<? extends Number>?
Question 4 of 5
What happens to type parameters at runtime?
Question 5 of 5
<T extends A & B> means T must:
0
/ 5
Quiz complete!

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 T for reading, ? super T for writing, ? for any.
  • Primitives are not allowed as type parameters — use wrapper types.
  • Type parameters are erased at runtime; JVM sees Object.
Africa & India's Best AI Academy
🤖 AI-first 🎓 Placement Assistance

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 →