Generics in Java enable types (classes and interfaces) to be parameters when defining classes, interfaces, and methods. They provide a way to reuse the same code with different data types while ensuring type safety.
Generics allow you to define classes, interfaces, and methods with a placeholder for the type they operate on. This placeholder is replaced with a specific type when the code is executed.
public class Box<T> {
private T value;
public void setValue(T value) {
this.value = value;
}
public T getValue() {
return value;
}
public static void main(String[] args) {
Box<Integer> intBox = new Box<>();
intBox.setValue(10);
System.out.println("Integer Value: " + intBox.getValue());
Box<String> strBox = new Box<>();
strBox.setValue("Hello");
System.out.println("String Value: " + strBox.getValue());
}
}
Integer Value: 10
String Value: Hello
Type safety ensures that a variable is only assigned values of a specific type. Generics provide compile-time type checking, which helps catch errors early in the development process.
Without generics, you might use Object
to hold different types, which requires casting and can lead to runtime errors: