Introduction
In Java programming, developers often need to create classes that work with different types of data. Before Java 5, this was typically achieved by using the Object class, allowing a single class to store any type of object. However, this approach had several drawbacks. Developers had to perform explicit type casting when retrieving values, and incorrect casts could lead to runtime errors such as ClassCastException.
To address these issues, Java introduced Generics in Java 5. One of the most common applications of Generics is the Generic Class. A generic class allows you to define a class with one or more type parameters, enabling it to work with different data types while maintaining compile-time type safety.
Generic classes are extensively used in the Java Collections Framework, custom data structures, utility libraries, enterprise frameworks, and reusable APIs. They improve code quality, eliminate unnecessary casting, and make programs easier to understand and maintain.
What is a Java Generic Class?
A Generic Class is a class that uses one or more type parameters instead of a fixed data type.
The actual data type is specified when an object of the class is created.
Instead of writing separate classes for different data types, one generic class can handle many types.
For example, the same class can store:
- Strings
- Integers
- Doubles
- Characters
- Custom objects
This makes the class reusable and type-safe.
Why Use Generic Classes?
Generic classes offer several advantages:
- Compile-time type checking
- Eliminate explicit type casting
- Increase code reusability
- Reduce duplicate code
- Improve readability
- Prevent runtime type errors
- Simplify API development
Instead of creating separate classes for each data type, one generic class can serve all of them.
Syntax of a Generic Class
class ClassName {
// Class members
}
Where:
- T is the type parameter.
- It acts as a placeholder for the actual type.
Example:
Box box =
new Box<>();
Here, T becomes String.
Creating a Generic Class
The following example creates a generic class named Box.
class Box {
private T value;
public void setValue(T value) {
this.value = value;
}
public T getValue() {
return value;
}
}
This class can store any object type.
Using a Generic Class
Example with String
public class Main {
public static void main(String[] args) {
Box box =
new Box<>();
box.setValue("Java");
System.out.println(
box.getValue()
);
}
}
Output
Example with Integer
public class Main {
public static void main(String[] args) {
Box box =
new Box<>();
box.setValue(100);
System.out.println(
box.getValue()
);
}
}
Output
The same class works for different data types.
Multiple Type Parameters
A generic class can have multiple type parameters.
Example
class Pair {
private K key;
private V value;
Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
}
Using the class:
Pair<Integer, String> student =
new Pair<>(101, "Rahul");
Here:
- K represents the key.
- V represents the value.
Bounded Generic Classes
Sometimes, a generic class should accept only certain types.
Java provides bounded type parameters using the extends keyword.
Example
class Calculator {
private T number;
Calculator(T number) {
this.number = number;
}
public double square() {
return number.doubleValue()
* number.doubleValue();
}
}
Valid:
Calculator c1 =
new Calculator<>(10);
Calculator c2 =
new Calculator<>(4.5);
Invalid:
Calculator c =
new Calculator<>("Java");
String is not a subclass of Number, so it cannot be used.
Generic Constructor
A generic class can also contain constructors.
class Student {
private T id;
Student(T id) {
this.id = id;
}
public T getId() {
return id;
}
}
Usage:
Student s =
new Student<>(101);
System.out.println(
s.getId()
);
The constructor accepts the generic type parameter.
Generic Class with Methods
Generic classes can include normal methods.
class Printer {
private T value;
Printer(T value) {
this.value = value;
}
public void print() {
System.out.println(value);
}
}
Usage:
Printer p =
new Printer<>("Hello");
p.print();
Output
Generic Class in the Java Collections Framework
Many Java collection classes are generic.
Example
ArrayList names =
new ArrayList<>();
names.add("Rahul");
names.add("Amit");
for(String name : names) {
System.out.println(name);
}
Benefits:
- Type safety
- No explicit casting
- Cleaner code
Collections such as ArrayList, HashMap, HashSet, and LinkedList all use Generic Classes internally.
Real-Life Example
Suppose an online shopping application stores product information.
class Product {
private T productId;
Product(T productId) {
this.productId = productId;
}
public T getProductId() {
return productId;
}
}
public class Main {
public static void main(String[] args) {
Product p1 =
new Product<>(101);
Product p2 =
new Product<>("A501");
System.out.println(
p1.getProductId()
);
System.out.println(
p2.getProductId()
);
}
}
Output
A501
The same class supports different types of product identifiers without code duplication.
Generic Class vs Normal Class
| Generic Class | Normal Class |
|---|---|
| Uses type parameters | Uses fixed data types |
| Reusable for different object types | Separate classes may be required for different data types |
| Provides compile-time type safety | May require explicit casting when using Object |
| Reduces duplicate code | Can lead to repeated implementations |
| Widely used in collections and frameworks | Suitable for fixed-type scenarios |
Advantages of Generic Classes
- Compile-time type safety
- Eliminates explicit casting
- Improves code reuse
- Reduces runtime errors
- Enhances readability
- Simplifies maintenance
- Supports reusable libraries and frameworks
Common Mistakes
1. Using Raw Types
Incorrect:
Box box =
new Box();
Correct:
Box<String> box =
new Box<>();
Using raw types bypasses generic type checking.
2. Using Primitive Types
Incorrect:
Box<Int> box;
Generics cannot work with primitive types.
Correct:
Box<Integer> box;
Always use wrapper classes such as Integer, Double, or Boolean.
3. Ignoring Type Bounds
If a class uses bounded Generics, only compatible types should be supplied.
4. Assuming Generic Information Exists at Runtime
Because of type erasure, generic type information is removed during compilation.
5. Using Generic Classes Unnecessarily
If a class will always work with a single fixed data type, a generic class may add unnecessary complexity.
Best Practices
- Always specify type parameters instead of using raw types.
- Use meaningful type parameter names such as T, E, K, and V.
- Apply bounded Generics when appropriate.
- Prefer Generic Classes over using Object.
- Use wrapper classes instead of primitive types.
- Keep generic APIs simple and easy to understand.
- Document generic type parameters in public APIs.
Conclusion
Java Generic Classes are a powerful feature introduced in Java 5 that enables developers to create flexible, reusable, and type-safe classes. By replacing fixed data types with type parameters, a single class can work seamlessly with different object types while maintaining compile-time type checking.
Generic Classes are a fundamental part of modern Java development and form the backbone of the Java Collections Framework and many enterprise libraries. By understanding how to create and use Generic Classes, applying bounded type parameters where appropriate, and following best practices, you can write cleaner, safer, and more maintainable Java applications.