Generic classes and type parameters

In Java, Generic classes  allow you to write flexible, reusable, and type-safe code by enabling classes, interfaces, and methods to operate on objects of various types while providing compile-time type checking.

Generic Classes

A generic class is a class that can work with any data type, specified via a type parameter. The type parameter acts as a placeholder for the actual type that will be used when an instance of the class is created.

Syntax
class ClassName<T> {
    // T is the type parameter
    private T data;

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

    public T getData() {
        return data;
    }
}
T is a type parameter (can be any identifier, e.g., E, K, V).
The actual type is specified when instantiating the class.Code language: PHP (php)

 Program

public class Box<T> {
    private T content;

    public Box(T content) {
        this.content = content;
    }

    public T getContent() {
        return content;
    }

    public static void main(String[] args) {
        Box<Integer> intBox = new Box<>(123); // T is Integer
        Box<String> strBox = new Box<>("Hello"); // T is String

        System.out.println(intBox.getContent()); // Output: 123
        System.out.println(strBox.getContent()); // Output: Hello
    }
}Code language: PHP (php)

2. Type Parameters

Type parameters are placeholders for types in generic classes, interfaces, or methods. They are defined within angle brackets (< >) and follow certain conventions.

Common Type Parameter Names
  • T: General type.
  • E: Element (used in collections).
  • K: Key (used in maps).
  • V: Value (used in maps).
  • N: Number.
Multiple Type Parameters

A generic class can have multiple type parameters:

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 static void main(String[] args) {
         Pair<String, Integer> pair = new Pair<>("Age", 30);
         System.out.println(pair.getKey() + ": " + pair.getValue()); // Output: Age: 30
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 static void main(String[] args) {
         Pair<String, Integer> pair = new Pair<>("Age", 30);
         System.out.println(pair.getKey() + ": " + pair.getValue());// Output: Age: 30
    }
}Code language: PHP (php)
Scroll to Top