Generic Classes
A class that can refer to any type is known as a Generic Class.
When you write a generic class, you use a parameter placeholder (like <T>) instead of a specific data type (like Integer or String). When the class is instantiated, the programmer provides the actual type they want to use, and the compiler effectively replaces all instances of <T> with that exact type.
Type Parameter Naming Conventions
By convention, type parameter names are single, uppercase letters. This makes it easy to distinguish a type parameter from an ordinary class or interface name.
The most commonly used type parameters are:
T- Type (The most generic placeholder)E- Element (used extensively by the Java Collections Framework)K- Key (Used in Maps)V- Value (Used in Maps)N- Number
Creating a Generic Class
Let's create a generic class called Box<T>. This box can hold an object of whatever type we specify when we create the object.
// 1. Declare the type parameter <T> after the class name
class Box<T> {
// 2. Use T as the data type for variables
private T objectInside;
// 3. Use T in method parameters
public void add(T object) {
this.objectInside = object;
}
// 4. Use T as the return type
public T get() {
return objectInside;
}
}
public class LabGenericClass1 {
public static void main(String args[]) {
// Creating a Box specifically for Integers
Box<Integer> integerBox = new Box<>();
integerBox.add(10);
// integerBox.add("Hello"); // COMPILE ERROR!
System.out.println("Integer Value: " + integerBox.get());
// Creating a Box specifically for Strings
Box<String> stringBox = new Box<>();
stringBox.add("Hello World");
System.out.println("String Value: " + stringBox.get());
}
}
Multiple Type Parameters
A generic class can have more than one type parameter. For example, a map entry needs both a Key and a Value. You separate multiple type parameters with commas.
// Class with two type parameters: K and V
class Pair<K, V> {
private K key;
private V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
}
public class LabGenericClass2 {
public static void main(String args[]) {
// K is String, V is Integer
Pair<String, Integer> p1 = new Pair<>("Age", 30);
System.out.println(p1.getKey() + ": " + p1.getValue());
// K is Integer, V is String
Pair<Integer, String> p2 = new Pair<>(101, "Alice");
System.out.println("ID " + p2.getKey() + " belongs to " + p2.getValue());
}
}
[!WARNING] You cannot use primitive data types (like
int,double,char) as type parameters for generic classes. You must use their corresponding Wrapper classes (Integer,Double,Character).