Generic Constructor
A Generic Constructor is a constructor that defines its own type parameter(s) independent of the class’s type parameters.
Even if the class is not generic, the constructor can be.
Syntax of a Generic Constructor
class ClassName {
<T> ClassName(T param) {
// constructor logic
}
}
//The <T> appears before the constructor name.Code language: PHP (php)
Example 1: Generic Constructor in a Non-Generic Class
public class Printer {
public <T> Printer(T message) {
System.out.println("Constructor received: " + message);
}
public static void main(String[] args) {
Printer p1 = new Printer("LotusJavaPrince");
Printer p2 = new Printer(100);
}
}
/*
Constructor received: LotusJavaPrince
Constructor received: 100
*/
Example 2: Generic Constructor in a Generic Class
public class Holder<T> {
private T value;
// Generic constructor inside generic class
public <U> Holder(U input) {
System.out.println("Generic Constructor with: " + input);
}
public void setValue(T value) {
this.value = value;
}
}
Generic Static Methods
Since static methods belong to the class, and not instances, they cannot use class-level type parameters (like T in class Box<T>). So, if you want a static method to be generic, you must declare its own type parameters.
public class Utility {
public static <T> void print(T item) {
System.out.println("Item: " + item);
}
}Code language: PHP (php)
Program
public class Utility {
public static <T> void display(T value) {
System.out.println("Displaying: " + value);
}
public static <T, U> void showPair(T key, U value) {
System.out.println("Key: " + key + ", Value: " + value);
}
public static void main(String[] args) {
Utility.display("Mahesh");
Utility.display(2025);
Utility.showPair("ID", 101);
}
}
/*
Displaying: Mahesh
Displaying: 2025
Key: ID, Value: 101
*/