Generics
Generic classes, methods, bounded generics, wildcards, type erasure
- Design type-safe generic classes and methods
- Apply bounded generics with extends and super
- Master wildcards: upper bound, lower bound, unbounded
- Understand type erasure and its implications
Series:
Java Core Concepts | Chapter: Generic Classes & Methods Audience: Intermediate Java Developers Coverage: Generic Classes, Generic Methods, Bounded Generics, Wildcards, Raw Types, Type Erasure
Table of Contents
- The Problem Generics Solve
- What are Generics?
- Generic Classes
- Inheritance with Generic Classes
- Multiple Type Parameters
- Generic Methods
- Raw Types
- Bounded Generics
- Wildcards
- Generic Type Parameter vs Wildcard — When to Use Which
- Type Erasure
- Interview Question Bank
- Master Summary
Mind Map Generics Overview
1. The Problem Generics Solve
The Starting Problem Using `Object` as a Universal Type
Before understanding generics, let's understand why they were needed.
Since Object is the parent of all classes in Java, a variable of type Object can hold a reference to any object. This seems powerful — but it creates a painful problem: you always have to typecast, and you can make mistakes at runtime.
Example The Pre-Generics Approach
1class Print {2 Object value;3
4 void setPrintValue(Object value) {5 this.value = value;6 }7
8 Object getPrintValue() {9 return value;10 }11}12
13public class Main {14 public static void main(String[] args) {15 Print obj = new Print();16
17 // Storing an Integer18 obj.setPrintValue(1);19 int intVal = (int) obj.getPrintValue(); // Must typecast — tedious20
21 // Storing a String — also accepted (no restriction)22 obj.setPrintValue("Hello");23
24 // Now what type does this hold? Integer? String? Something else?25 // You have no idea without tracking it manually.26 Object val = obj.getPrintValue();27
28 if (val instanceof Integer) {29 int v = (int) val;30 } else if (val instanceof String) {31 String v = (String) val;32 }33 // ... and so on for every possible type34 }35}Problems with This Approach
| Problem | Explanation |
|---|---|
| Mandatory typecasting | Every get call requires a cast — verbose and error-prone |
| No type safety | You can store any type accidentally — no compile-time check |
| Runtime ClassCastException | If you cast to the wrong type, the program crashes at runtime, not at compile time |
| No expressive API | Code readers can't tell what type a Print object is supposed to hold |
2. What are Generics?
Definition
Generics allow you to write classes, interfaces, and methods where the type of data being operated on is specified as a parameter. Instead of hardcoding Object, you define a placeholder (like T) that is replaced with a concrete type when the code is used.
A generic class is a class that is parameterized over types.
Syntax The Diamond Operator
The diamond operator <> is used to declare and use type parameters:
1ClassName<TypeParameter>Common type parameter naming conventions (just conventions — you can use any letter):
| Letter | Common Usage |
|---|---|
T | Type (general purpose) |
E | Element (used in collections) |
K | Key (used in maps) |
V | Value (used in maps) |
N | Number |
R | Return type |
3. Generic Classes
Syntax
1class ClassName<T> {2 T value; // T used as field type3
4 void setValue(T value) {5 this.value = value;6 }7
8 T getValue() {9 return value;10 }11}Converting the `Print` Class to Generic
1// BEFORE — using Object (problem-prone)2class Print {3 Object value;4 void setPrintValue(Object value) { this.value = value; }5 Object getPrintValue() { return value; }6}7
8// AFTER — using Generic (type-safe)9class Print<T> {10 T value;11 void setPrintValue(T value) { this.value = value; }12 T getPrintValue() { return value; }13}Using the Generic Class
1public class Main {2 public static void main(String[] args) {3 // Create a Print for Integer4 Print<Integer> intObj = new Print<>();5 intObj.setPrintValue(42);6 int val = intObj.getPrintValue(); // No cast needed!7 System.out.println(val); // 428
9 // Create a Print for String10 Print<String> strObj = new Print<>();11 strObj.setPrintValue("Hello Generics");12 String str = strObj.getPrintValue(); // No cast needed!13 System.out.println(str); // Hello Generics14
15 // Type safety at compile time:16 // intObj.setPrintValue("Hello"); // ❌ Compile error — can only accept Integer17 }18}42 Hello Generics
Line-by-Line Explanation
| Code | Explanation |
|---|---|
Print | Tell Java: replace T with Integer for this object |
Print | Tell Java: replace T with String for this object |
intObj.getPrintValue() | Returns Integer — no cast needed because compiler knows the type |
intObj.setPrintValue("Hello") | ❌ Compile error — type constraint enforced at compile time |
What Can Replace `T`?
1Print<Integer> p1 = new Print<>(); // ✅ Integer (wrapper class)2Print<String> p2 = new Print<>(); // ✅ String3Print<MyClass> p3 = new Print<>(); // ✅ Any custom class4Print<int> p4 = new Print<>(); // ❌ Compile error — int is primitive5Print<double> p5 = new Print<>(); // ❌ Compile error — double is primitiveUse wrapper classes for primitives: int → Integer, double → Double, etc.
Before vs After Generics Comparison
| Aspect | Without Generics (Object) | With Generics (T) |
|---|---|---|
| Type safety | ❌ None | ✅ Compile-time |
| Typecasting | ❌ Required everywhere | ✅ Not needed |
| Error detection | ❌ Runtime (ClassCastException) | ✅ Compile time |
| Code clarity | ❌ Unclear what type is stored | ✅ Explicitly declared |
| Multiple types accidentally | ❌ Can mix types | ✅ Constrained to one |
4. Inheritance with Generic Classes
A generic class can be extended just like a regular class. The behavior depends on whether the subclass is generic or non-generic.
Case 1 Non-Generic Subclass
When the subclass is not generic, it must specify the type parameter at the point of extends — locking in the type for good.
1class Print<T> {2 T value;3 T getPrintValue() { return value; }4 void setPrintValue(T value) { this.value = value; }5}6
7// Non-generic subclass — must specify T at extends8class ColorPrint extends Print<String> {9 String color;10}1public class Main {2 public static void main(String[] args) {3 ColorPrint cp = new ColorPrint(); // No diamond needed — not generic4 cp.setPrintValue("Vivid Blue"); // Only String accepted5 System.out.println(cp.getPrintValue()); // Vivid Blue6 }7}Vivid Blue
The type is fixed atStringfor allColorPrintobjects. You cannot create aColorPrintof Integer.
Case 2 Generic Subclass
When the subclass is also generic, it passes the type parameter through. The concrete type is specified only at object creation time.
1class ColorPrint<T> extends Print<T> {2 // T flows through from Print<T>3 String color;4}1public class Main {2 public static void main(String[] args) {3 ColorPrint<String> cs = new ColorPrint<>();4 cs.setPrintValue("Ocean Blue");5 System.out.println(cs.getPrintValue()); // Ocean Blue6
7 ColorPrint<Integer> ci = new ColorPrint<>();8 ci.setPrintValue(100);9 System.out.println(ci.getPrintValue()); // 10010 }11}Ocean Blue 100
Inheritance Diagram
Summary Generic vs Non-Generic Subclass
| Aspect | Non-Generic Subclass | Generic Subclass |
|---|---|---|
| Type fixed at | extends declaration | Object creation time |
| Flexibility | Low — one type forever | High — any type per object |
| Syntax | class Child extends Parent | class Child |
5. Multiple Type Parameters
A generic class can have more than one type parameter, separated by commas inside the diamond.
Example Key-Value Pair
1class Pair<K, V> {2 K key;3 V value;4
5 void put(K key, V value) {6 this.key = key;7 this.value = value;8 }9
10 K getKey() { return key; }11 V getValue() { return value; }12}Using the Pair Class
1public class Main {2 public static void main(String[] args) {3 // K = String, V = Integer4 Pair<String, Integer> pair = new Pair<>();5 pair.put("Age", 25);6 System.out.println(pair.getKey() + ": " + pair.getValue()); // Age: 257
8 // K = Integer, V = String9 Pair<Integer, String> pair2 = new Pair<>();10 pair2.put(101, "Shreyansh");11 System.out.println(pair2.getKey() + ": " + pair2.getValue()); // 101: Shreyansh12 }13}Age: 25 101: Shreyansh
Two Valid Object Creation Syntaxes
1// Syntax 1 — type specified on both sides2Pair<String, Integer> p1 = new Pair<String, Integer>();3
4// Syntax 2 — type inferred from left side (diamond inference)5Pair<String, Integer> p2 = new Pair<>(); // preferred — less verboseBoth are correct. Syntax 2 is preferred in modern Java (Java 7+) because the compiler can infer the type from the left side.
6. Generic Methods
Overview
You don't always need to make an entire class generic. Sometimes only one or two methods need to work with a type parameter. Java allows you to make individual methods generic while keeping the class itself non-generic.
Syntax
1// Return type is void, type parameter T declared BEFORE the return type2public <T> void methodName(T parameter) {3 // use T here4}5
6// Return type uses T7public <T> T methodName(T parameter) {8 return parameter;9}Example Generic Method in a Non-Generic Class
1class GenericMethodClass {2 // Non-generic class — but contains a generic method3
4 public <T> void printValue(T value) {5 System.out.println("Value: " + value);6 System.out.println("Type: " + value.getClass().getSimpleName());7 }8}9
10public class Main {11 public static void main(String[] args) {12 GenericMethodClass gm = new GenericMethodClass();13
14 gm.printValue(42); // T = Integer15 gm.printValue("Hello"); // T = String16 gm.printValue(3.14); // T = Double17
18 // Custom class19 // gm.printValue(new Bus()); // T = Bus — works too20 }21}Value: 42 Type: Integer Value: Hello Type: String Value: 3.14 Type: Double
Generic Method vs Generic Class Scope Difference
| Aspect | Generic Class | Generic Method |
|---|---|---|
Where T is available | Entire class (all methods, fields) | Only within that one method |
| Declared at | Class name | Before return type of method |
| Object creation | new Print | No change at call site |
7. Raw Types
Definition
A raw type is when you use a generic class without specifying any type parameter. When you don't supply a type, the compiler internally treats the type parameter as Object.
Example
1class Print<T> {2 T value;3 void setPrintValue(T value) { this.value = value; }4 T getPrintValue() { return value; }5}6
7public class Main {8 public static void main(String[] args) {9 // Parameterized type — type-safe10 Print<String> parameterized = new Print<>();11 parameterized.setPrintValue("Hello");12 // parameterized.setPrintValue(42); // ❌ Compile error13
14 // Raw type — no type specified15 Print raw = new Print(); // internally: Print<Object>16 raw.setPrintValue("Hello"); // ✅ accepted17 raw.setPrintValue(42); // ✅ also accepted — no restriction18 raw.setPrintValue(new Object()); // ✅ also accepted19 }20}What Happens Internally
1// What you write:2Print raw = new Print();3
4// What the compiler sees internally:5Print<Object> raw = new Print<Object>(); // Object is substituted for TSince Object is the parent of all, the raw type accepts anything — which defeats the purpose of generics.
ClassCastException at runtime, and generate compiler warnings. Raw types exist primarily for backward compatibility with pre-Java 5 code.8. Bounded Generics
Overview
By default, a type parameter T can be replaced with any reference type. Bounded generics let you restrict what types can be used as the type argument — only a specific class/interface hierarchy is allowed.
Upper Bound `extends`
Definition
An upper bound restricts T to be either the specified class/interface OR any of its subclasses.
Syntax
1class ClassName<T extends UpperBoundClass> {2 // T can be UpperBoundClass or any class that extends it3}The Class Hierarchy for This Example
Example
1class Print<T extends Number> { // T can only be Number or its subclasses2 T value;3
4 void setPrintValue(T value) { this.value = value; }5 T getPrintValue() { return value; }6}7
8public class Main {9 public static void main(String[] args) {10 Print<Integer> intPrint = new Print<>(); // ✅ Integer extends Number11 Print<Double> dblPrint = new Print<>(); // ✅ Double extends Number12 Print<Float> fltPrint = new Print<>(); // ✅ Float extends Number13
14 // Print<String> strPrint = new Print<>(); // ❌ Compile error — String doesn't extend Number15 }16}extends keyword here is not the same as class inheritance extends. In the bounded type parameter context:
- For a class → T extends SomeClass means T must be SomeClass or its subclass
- For an interface → T extends SomeInterface (NOT implements) — same syntax even for interfacesAdvantage Methods of the Bound Are Available
When you bound T extends Number, inside the generic class you can call Number's methods on T:
1class NumericPrint<T extends Number> {2 T value;3
4 void printDoubleValue() {5 // Since T is guaranteed to be a Number, we can call Number's methods6 System.out.println(value.doubleValue()); // ✅ available because T extends Number7 }8}Without the bound, you couldn't call .doubleValue() because T could be anything.
Multi-Bound `extends` with Multiple Interfaces
Definition
A multi-bound type parameter requires that the type argument extend one class AND implement one or more interfaces simultaneously.
Background Java Inheritance Rules (Recap)
| Rule | Explanation |
|---|---|
A class can extend only ONE class | No multiple class inheritance in Java (Diamond Problem) |
A class can implement multiple interfaces | No conflict — interfaces have no implementation |
Multi-bound generics mirror this: the first bound must be a concrete/abstract class, and subsequent bounds must be interfaces.
Syntax
1class ClassName<T extends ParentClass & Interface1 & Interface2> {2 // T must extend ParentClass AND implement Interface1 AND Interface23}&. If you list an interface before a class, you get a compile error.Example
1class ParentClass { }2interface Interface1 { void method1(); }3interface Interface2 { void method2(); }4
5// Multi-bound: T must extend ParentClass AND implement Interface1 AND Interface26class Print<T extends ParentClass & Interface1 & Interface2> {7 T value;8 void setValue(T val) { this.value = val; }9}10
11// Class A — satisfies all constraints12class A extends ParentClass implements Interface1, Interface2 {13 public void method1() { }14 public void method2() { }15}16
17// Class B — only implements one interface18class B extends ParentClass implements Interface1 {19 public void method1() { }20 // Missing Interface2!21}22
23public class Main {24 public static void main(String[] args) {25 Print<A> validPrint = new Print<>(); // ✅ A satisfies all bounds26 // Print<B> invalidPrint = new Print<>(); // ❌ B doesn't implement Interface227 }28}Bounded Generics Diagram
9. Wildcards
The Problem Wildcards Solve
Consider this class hierarchy:
1Vehicle2├── Bus3└── CarYou know that Bus is a subtype of Vehicle. But is List a subtype of List?
No. And this is crucial to understand.
1Vehicle vehicleObj = new Bus(); // ✅ Valid — parent ref holds child object2
3List<Vehicle> vehicleList = new ArrayList<>();4List<Bus> busList = new ArrayList<>();5
6vehicleList = busList; // ❌ Compile error — List<Bus> is NOT a subtype of List<Vehicle>7busList = vehicleList; // ❌ Compile error — same reasonWhy Isn't `List<Bus>` a Subtype of `List<Vehicle>`?
Because List allows adding Car objects (also a Vehicle). If List were assignable to List, someone could add a Car to what is really a List — which would be wrong.
1// HYPOTHETICAL (Java correctly prevents this)2List<Vehicle> ref = busList; // If this were allowed...3ref.add(new Car()); // ...this would corrupt the busList with a Car!Java prevents this to protect type safety. This is called invariance — generic types are invariant by default.
The Consequence
1class Print {2 // This method only accepts List<Vehicle> — not List<Bus> or List<Car>3 void setPrintValues(List<Vehicle> vehicles) { ... }4}5
6List<Vehicle> vList = new ArrayList<>();7List<Bus> bList = new ArrayList<>();8
9print.setPrintValues(vList); // ✅10print.setPrintValues(bList); // ❌ Compile error — List<Bus> ≠ List<Vehicle>This is where wildcards come in.
Wildcard Syntax The `?` Operator
The wildcard ? is a special type argument that means "unknown type". It makes generic types flexible in ways that regular type parameters don't.
There are three forms:
| Wildcard | Syntax | Meaning |
|---|---|---|
| Upper Bound | ? extends Type | Type or any subclass |
| Lower Bound | ? super Type | Type or any superclass |
| Unbounded | ? | Any type |
Wildcard Type 1 Upper Bound (`? extends`)
Accepts: the specified type AND all its subclasses.
1class Print {2 // Accepts List<Vehicle>, List<Bus>, List<Car>3 void setPrintValues(List<? extends Vehicle> vehicles) {4 for (Vehicle v : vehicles) {5 System.out.println(v);6 }7 }8}9
10public class Main {11 public static void main(String[] args) {12 Print p = new Print();13
14 List<Vehicle> vList = new ArrayList<>();15 List<Bus> bList = new ArrayList<>();16 List<Car> cList = new ArrayList<>();17
18 p.setPrintValues(vList); // ✅ Vehicle itself19 p.setPrintValues(bList); // ✅ Bus extends Vehicle20 p.setPrintValues(cList); // ✅ Car extends Vehicle21 }22}Wildcard Type 2 Lower Bound (`? super`)
Accepts: the specified type AND all its superclasses.
1class Print {2 // Accepts List<Vehicle>, List<Object> (superclasses of Vehicle)3 // Does NOT accept List<Bus>, List<Car> (subclasses of Vehicle)4 void addVehicles(List<? super Vehicle> vehicles) {5 vehicles.add(new Vehicle());6 }7}8
9public class Main {10 public static void main(String[] args) {11 Print p = new Print();12
13 List<Vehicle> vList = new ArrayList<>();14 List<Object> oList = new ArrayList<>();15 List<Bus> bList = new ArrayList<>();16
17 p.addVehicles(vList); // ✅ Vehicle itself18 p.addVehicles(oList); // ✅ Object is superclass of Vehicle19 // p.addVehicles(bList); // ❌ Bus is a subclass, not superclass20 }21}Wildcard Type 3 Unbounded (`?`)
Accepts: any type whatsoever.
Use this when your method only needs to work with methods from Object (the parent of all), because that's the only thing you can safely call — you don't know what the actual type is.
1class Print {2 void printList(List<?> list) {3 for (Object item : list) {4 // Can only call Object methods — .toString(), .hashCode(), etc.5 System.out.println(item);6 }7 }8}9
10public class Main {11 public static void main(String[] args) {12 Print p = new Print();13
14 List<Integer> ints = List.of(1, 2, 3);15 List<String> strings = List.of("a", "b", "c");16 List<Vehicle> vehicles = new ArrayList<>();17
18 p.printList(ints); // ✅19 p.printList(strings); // ✅20 p.printList(vehicles); // ✅21 }22}List>, you cannot add elements to the list (except null) because the compiler doesn't know what type the list holds. You can only read from it (as Object).10. Generic Type Parameter vs Wildcard When to Use Which
This is a subtle but important distinction. Here's a clear breakdown:
Key Differences
| Feature | Generic Type | Wildcard extends Number> |
|---|---|---|
| Multiple parameters same type | ✅ Enforces same type across params | ❌ Each ? can be different type |
Lower bound (super) | ❌ Not supported | ✅ Supported |
| Multiple type params | ✅ | ❌ One ? only per use |
| Flexibility | More structured/restrictive | More flexible |
| When to use | When parameters must share the same type | When you just need to accept a range of types |
Example The Critical Difference
1// WILDCARD — source and destination can be DIFFERENT types (both just extend Number)2void computeList(List<? extends Number> source, List<? extends Number> destination) {3 // source could be List<Integer>, destination could be List<Double>4 // No enforcement that they're the same type5}6
7// GENERIC TYPE — source and destination MUST be the SAME type8<T extends Number> void computeList(List<T> source, List<T> destination) {9 // If source is List<Integer>, destination MUST also be List<Integer>10}1List<Integer> intList = new ArrayList<>();2List<Double> doubleList = new ArrayList<>();3
4// With wildcard:5computeListWildcard(intList, doubleList); // ✅ Different types OK6
7// With generic type:8// computeListGeneric(intList, doubleList); // ❌ Compile error — T can't be both Integer and Double9computeListGeneric(intList, intList); // ✅ Same type OKDecision Guide
11. Type Erasure
What is Type Erasure?
Type erasure is the process by which the Java compiler removes all generic type information when generating bytecode. Generics are a compile-time feature only — at runtime, the JVM knows nothing about type parameters.
All type parameters are replaced with either:
Object(for unbounded types)- The upper bound class (for bounded types like
T extends Number→ replaced withNumber)
Examples of Type Erasure
Unbounded Generic Class
1// What you write:2class Print<T> {3 T value;4 T getPrintValue() { return value; }5 void setPrintValue(T value) { this.value = value; }6}7
8// What the bytecode looks like after erasure:9class Print {10 Object value;11 Object getPrintValue() { return value; }12 void setPrintValue(Object value) { this.value = value; }13}Bounded Generic Class
1// What you write:2class Print<T extends Number> {3 T value;4 T getPrintValue() { return value; }5}6
7// What the bytecode looks like after erasure:8class Print {9 Number value; // T replaced with upper bound: Number10 Number getPrintValue() { return value; }11}Generic Method
1// What you write:2public <T> void printValue(T value) {3 System.out.println(value);4}5
6// What the bytecode looks like after erasure:7public void printValue(Object value) { // T replaced with Object8 System.out.println(value);9}10
11// Bounded generic method:12public <T extends Bus> void setValue(T val) { ... }13
14// After erasure:15public void setValue(Bus val) { ... } // T replaced with BusWhy Does Type Erasure Exist?
Type erasure was introduced to maintain backward compatibility with pre-Java 5 code (before generics were added). Existing bytecode and libraries that used raw types (List, Map) could continue to work unchanged.
Consequences of Type Erasure
| Consequence | Explanation |
|---|---|
Cannot use instanceof with type params | if (obj instanceof T) → ❌ T is erased at runtime |
| Cannot create instances of T | new T() → ❌ Compiler doesn't know what T is at runtime |
| Cannot create arrays of parameterized types | new T[10] → ❌ |
List and List are same class at runtime | Both become List after erasure |
1class Example<T> {2 void test(Object obj) {3 // if (obj instanceof T) { } // ❌ Compile error — T is erased4
5 // T t = new T(); // ❌ Compile error — can't instantiate T6
7 // T[] arr = new T[10]; // ❌ Compile error — can't create T array8 }9}Type Erasure Diagram
12. Interview Question Bank
Core Generics
| Question | Key Answer |
|---|---|
| What are generics in Java? | Write type-parameterized classes/methods; type specified at use time; shifts errors to compile time |
| Why were generics introduced? | Avoid typecasting, provide type safety, prevent ClassCastException at runtime |
| Can generics use primitive types? | No — only reference types; use wrapper classes (Integer, Double, etc.) |
| What is a type parameter? | Placeholder letter (T, K, V) replaced with actual type at compile time |
| What is the diamond operator? | <> — used to declare and use type parameters |
Generic Classes & Methods
| Question | Key Answer |
|---|---|
| How do you make a class generic? | Add after class name; use T as field/method types |
| How do you make a method generic? | Declare type param before return type: public |
| What is the scope of a generic method's type param? | Limited to that method only |
| What is a raw type? | Using a generic class without specifying type param; compiler uses Object internally; avoid in production |
| Can a non-generic class have generic methods? | Yes — the class itself is not generic, but specific methods can be |
Bounded Generics
| Question | Key Answer |
|---|---|
| What is an upper bound in generics? | T extends SomeClass — restricts T to SomeClass or its subclasses |
| What keyword is used for interface bounds? | Still extends (not implements) — e.g., T extends Comparable |
| What is a multi-bound type parameter? | T extends Class & Interface1 & Interface2 — class first, then interfaces |
| Can you have multiple class bounds? | No — only one class; multiple interfaces after & |
Wildcards
| Question | Key Answer |
|---|---|
| What is a wildcard? | ? — unknown type in generics; three forms: unbounded, upper bound, lower bound |
Is List a subtype of List? | No — generic types are invariant; use wildcards for flexibility |
What is List extends Animal>? | Upper bound wildcard — accepts List of Animal or any subclass |
What is List super Dog>? | Lower bound wildcard — accepts List of Dog or any superclass |
| When to use wildcard over generic type? | Lower bound needed, or when flexibility across different types is needed |
| When to use generic type over wildcard? | When multiple parameters must be the SAME type, or multiple type params needed |
Can you add to List>? | No (except null) — type is unknown, adding anything would be unsafe |
Type Erasure
| Question | Key Answer |
|---|---|
| What is type erasure? | Compiler removes generic type info at compile time; bytecode has no generics |
| What replaces unbounded T at runtime? | Object |
What replaces bounded T extends Number at runtime? | Number |
| Why does type erasure exist? | Backward compatibility with pre-Java 5 code |
Can you use instanceof with generic type T? | No — T is erased at runtime |
13. Master Summary
Quick Revision Bullets
- ✅ Problem with
Object: requires typecasting, no type safety, runtimeClassCastException - ✅ Generics = type parameters replace
Object; specified at compile time; type-safe; no casting needed - ✅ Only reference types — primitives not allowed; use wrapper classes (
int→Integer) - ✅ Generic class:
class Name— T usable across entire class (fields, methods) - ✅ Generic method:
public— T scoped to that method onlyvoid method(T param) - ✅ Non-generic subclass: must specify type at
extends:class Child extends Parent - ✅ Generic subclass: passes T through:
class Childextends Parent - ✅ Multiple type params:
class Pair— any number allowed - ✅ Raw type:
new GenericClass()without<>— compiler substitutesObject; avoid in production - ✅ Upper bound:
— T must be Number or subclass; unlocks Number's methods inside class - ✅ Multi-bound:
— class first, interfaces after& - ✅
Listis NOT a subtype ofList— generic types are invariant - ✅ Upper bound wildcard:
List extends Vehicle>— accepts Vehicle and subclasses - ✅ Lower bound wildcard:
List super Vehicle>— accepts Vehicle and superclasses - ✅ Unbounded wildcard:
List>— accepts anything; can only use Object methods - ✅ Wildcard vs Generic type: wildcard = flexible, supports lower bound; generic type = strict same-type enforcement across params, supports multiple type params
- ✅ Type erasure: all generics erased at compile → bytecode; unbounded T → Object; bounded T → upper bound class; exists for backward compatibility
- ✅ Cannot do at runtime (due to erasure):
instanceof T,new T(),new T[]
Stack class with push(T) and pop() methods
2. Write a generic method that finds the max element in a List>
3. Experiment with upper and lower bound wildcards on lists of your own class hierarchy
4. Compare bytecode (using javap -c) of a generic class vs its equivalent non-generic version to see type erasure in actionEnd of Chapter — Java Generics
Practice & Implement
Apply what you learned in Generics
Implement a generic `Stack<T>` with `push`, `pop` (throws if empty), `peek`, and `isEmpty`. Test with Integer and String.
30 20 false
Mastery check
How well can you recall this?
Finished this lesson?