Lesson 18: Generics
19 Jul 2026 1 min Swarnil Singhai
Generics let a class or method work with any type while the compiler still checks type safety — no casting, no ClassCastException at runtime.
Real-time example
A generic Repository<T> gives every entity type (User, Order, Product) the same save/find API without duplicating code per type.
class Repository<T> {
private List<T> items = new ArrayList<>();
void save(T item) { items.add(item); }
List<T> findAll() { return items; }
}
Repository<String> userRepo = new Repository<>();
userRepo.save("user-1");
// userRepo.save(42); // compile error - type safety enforced
What's happening
The compiler enforces that Repository<String> only ever holds Strings — the bug (wrong type) is caught before the program runs.
Generics push type errors from runtime crashes to compile-time errors — always a win.
Advertisement