Parametric polymorphism allows a function or a data type to be written generically so that it can handle values identically without depending on their type.

Examples

Java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public class Solution<T> {
    private T data;

    public Solution(T data) {
        this.data = data;
    }

    public T getData() {
        return data;
    }

    public static void main(String[] args) {
        Solution<Integer> intSolution = new Solution<>(10);
        Solution<String> stringSolution = new Solution<>("Hello");
        System.out.println(intSolution.getData());       // Output: 10
        System.out.println(stringSolution.getData());    // Output: Hello
    }
}

Python

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from typing import TypeVar, Generic

T = TypeVar('T')

class Solution(Generic[T]):
    def __init__(self, data: T):
        self.data = data

    def get_data(self) -> T:
        return self.data

# Example usage
int_solution = Solution(10)
string_solution = Solution("Hello")
print(int_solution.get_data())  # Output: 10
print(string_solution.get_data())  # Output: Hello