Generics allow classes, interfaces, and methods to work with different data types while maintaining compile-time type safety. By using type parameters, developers can write reusable code that operates on multiple data types without sacrificing type checking or requiring explicit type casting.
Key Points: • Generics catch type-related errors at compile time, reducing the risk of ClassCastException at runtime. • They eliminate the need to write separate implementations for different data types, promoting code reuse. • Generics improve code readability by clearly specifying the types a class or method is intended to work with.
Example: Without generics, you might need separate classes such as IntegerBox, StringBox, and DoubleBox. With generics, a single Box<T> class can handle all these data types, reducing code duplication and improving maintainability.
Code Example:
class Box<T> {
private T value;
public void setValue(T value) {
this.value = value;
}
public T getValue() {
return value;
}
}
public class Main {
public static void main(String[] args) {
Box<String> stringBox =
new Box<>();
stringBox.setValue("Java");
Box<Integer> intBox =
new Box<>();
intBox.setValue(100);
System.out.println(
stringBox.getValue());
System.out.println(
intBox.getValue());
}
}Interview Tip: A concise interview answer is: Generics provide compile-time type safety by restricting objects to specific data types and reducing the need for explicit casting. They also eliminate code duplication by allowing a single class or method to work with multiple data types in a reusable and type-safe manner.