Skip to content
C

Generics

Generics allow you to write classes, interfaces, and methods that work with a specific type you decide when you actually use them, instead of fixing the type in advance. This is written using angle brackets, like <T>.


1. What are Generics?

Generics allow you to write classes, interfaces, and methods that work with a specific type you decide when you actually use them, instead of fixing the type in advance. This is written using angle brackets, like <T>.

2. Why is it used?

Generics allow the same class or method to work safely with different data types, while still catching type-related mistakes at compile-time, rather than causing unexpected errors while the program is running.

3. Real-Life Example

Think of a universal container that can be labeled to hold exactly one specific kind of item at a time — sometimes fruits, sometimes books — but once labeled, it strictly enforces that only that kind of item goes inside.

4. Syntax

java
class ClassName<T> { T value; } ClassName<String> obj = new ClassName<>();

5. Example Program

java
class Box<T> { T item; void setItem(T item) { this.item = item; } T getItem() { return item; } } public class GenericsDemo { public static void main(String[] args) { Box<String> box = new Box<>(); box.setItem("Java Book"); System.out.println("Item: " + box.getItem()); } }

Output:

Item: Java Book

6. Key Points to Remember

  • Generics catch type mismatches at compile-time, avoiding many runtime errors.
  • <T> is just a placeholder name — common conventions include T for type, E for element, K/V for key/value.
  • Collections like ArrayList<Integer> already use generics internally, which is why they only allow one specified type of element.