Java Generics – Complete Guide with Examples
Learn Java Generics to create type-safe classes, methods, and collections, understand generic types, wildcards, and how to use them for reusable and robust code.
Generics in Java – Complete Detailed Tutorial
Generics allow classes, interfaces, and methods to operate on types specified as parameters, providing compile-time type safety and reducing runtime errors.
1. What are Generics?
- Introduced in Java 5
- Parameterizes types (like templates in C++)
- Ensures type safety at compile time
- Eliminates need for casting objects
Syntax:
Tis a type parameter- Can also use E (Element), K (Key), V (Value), N (Number)
2. Generic Class Example
Output:
Key Points:
- Type specified at object creation
- Provides compile-time type checking
3. Generic Method
- Methods can also be generic
- Use
<T>before return type
Output:
4. Bounded Generics
- Restrict type parameter to subclass or interface
- Syntax:
T extends ClassName
Output:
Key Points:
- Ensures only Number subclasses used
- Avoids type errors at compile time
5. Wildcards in Generics
- Unbounded wildcard:
<?>– any type - Upper-bounded wildcard:
<? extends Class>– subclass of Class - Lower-bounded wildcard:
<? super Class>– superclass of Class
Output:
6. Key Points
- Generics provide type safety
- Reusability: same code works for multiple types
- Eliminates casting
- Works with classes, interfaces, methods, and collections
- Bounded types restrict type parameters
- Wildcards allow flexible method arguments
7. Summary
- Generics improve code readability, safety, and flexibility
- Widely used in Collections Framework
- Important for professional Java development