Mastering Java Generics – Building Reusable, Type‑Safe Code
Java Generics – Building Reusable, Type‑Safe Code
This guide explains Java generics, how to craft generic classes and methods, and the benefits they bring, illustrated with clear examples.
Java generics let you write one class, interface, or method that can operate on many different data types, while keeping compile‑time safety.
Note: Generics do not work with primitive types (int, float, char, etc).
Java Generics Class
By declaring a type parameter, you can create a class that works with any object type.
Example: Create a Generic Class
class Main {
public static void main(String[] args) {
GenericsClass<Integer> intObj = new GenericsClass<>(5);
System.out.println("Generic Class returns: " + intObj.getData());
GenericsClass<String> stringObj = new GenericsClass<>("Java Programming");
System.out.println("Generic Class returns: " + stringObj.getData());
}
}
class GenericsClass<T> {
private T data;
public GenericsClass(T data) { this.data = data; }
public T getData() { return this.data; }
}
Output
Generic Class returns: 5 Generic Class returns: Java Programming
In the example above, GenericsClass is a generic class where T is the type parameter. Two instances are created:
- intObj – T is replaced by
Integer, so the class works with integers. - stringObj – T is replaced by
String, so the class works with strings.
Java Generics Method
Methods can also be generic, allowing them to accept any type of argument while retaining type safety.
Example: Create a Generic Method
class Main {
public static void main(String[] args) {
DemoClass demo = new DemoClass();
demo.<String>genericsMethod("Java Programming");
demo.<Integer>genericsMethod(25);
}
}
class DemoClass {
public <T> void genericsMethod(T data) {
System.out.println("Generics Method:");
System.out.println("Data Passed: " + data);
}
}
Output
Generics Method: Data Passed: Java Programming Generics Method: Data Passed: 25
When the compiler can infer the type, you can omit the explicit type argument:
demo.genericsMethod("Java Programming");
Bounded Types
Sometimes you want a generic type to accept only a specific family of classes. Bounded types achieve this using the extends keyword.
Syntax: <T extends A> – T can be A or any subtype of A.
Example: Bounded Types
class GenericsClass <T extends Number> {
public void display() {
System.out.println("This is a bounded type generics class.");
}
}
class Main {
public static void main(String[] args) {
// GenericsClass<String> obj = new GenericsClass<>(); // compile‑time error
}
}
Here, GenericsClass accepts only numeric types (Integer, Double, etc.). Attempting to instantiate it with String causes a compile‑time error:
GenericsClass<String> obj = new GenericsClass<>();
^
reason: inference variable T has incompatible bounds
equality constraints: String
lower bounds: Number
where T is a type-variable:
T extends Number declared in class GenericsClass
Advantages of Java Generics
1. Code Reusability
Generic code can operate on multiple data types, reducing duplication. For instance, a single method can process integers, strings, and custom objects.
2. Compile‑Time Type Checking
Because the type parameter is known at compile time, the compiler can detect type mismatches before the program runs.
3. Seamless Integration with Collections
Java’s collection framework is generics‑based, enabling collections to enforce type safety. Examples:
ArrayList<String> list1 = new ArrayList<>();
ArrayList<Integer> list2 = new ArrayList<>();
Other collection classes (LinkedList, Queue, Map, etc.) also use generics for the same benefits.
Java
- Understanding Java’s final Keyword: Variables, Methods, and Classes
- Java instanceof Operator: A Comprehensive Guide
- Mastering Java Inheritance: Concepts, Types, and Practical Examples
- Understanding Java Nested Static Classes: Usage, Differences, and Examples
- Mastering Java Anonymous Inner Classes: Definition, Syntax, and Practical Examples
- Mastering Java’s ObjectInputStream: A Comprehensive Guide
- Mastering Java ObjectOutputStream: Serialization, Methods, and Practical Examples
- Mastering Java’s PrintStream Class: Print, Println, and Printf Explained
- Mastering Java Reader Class: Subclasses, Methods, and Practical Example
- Mastering Java File Operations with java.io – Creation, Reading, Writing & Deletion