Generic Classes

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • A Generic Class is a class declared with one or more type parameters (e.g., class Box<T>).
  • It acts as a template, allowing the class to handle different data types safely.
  • Standard type parameter naming conventions: E (Element), K (Key), V (Value), N (Number), T (Type).

Concept

Instead of writing a StringBox class and an IntegerBox class, you can write a single Box<T> class. When a developer instantiates the class, they provide the concrete type (e.g., new Box<String>()).

The type parameter <T> acts as a placeholder that the compiler replaces with the concrete type wherever <T> is used inside the class (like in fields, return types, or method parameters).

Examples

// A Generic Class with a single type parameter "T"
class Box<T> {
    private T content;

    public void set(T content) {
        this.content = content;
    }

    public T get() {
        return content;
    }
}

// A Generic Class with 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 void print() {
        System.out.println(key + " : " + value);
    }
}

public class GenericClassExample {
    public static void main(String[] args) {
        Box<String> stringBox = new Box<>();
        stringBox.set("Hello World");
        
        Box<Integer> intBox = new Box<>();
        intBox.set(42);
        
        Pair<Integer, String> errorCode = new Pair<>(404, "Not Found");
        errorCode.print();
    }
}

Interview Questions

Q: Can you instantiate a generic type parameter (e.g., new T())?
A: No. Because of Type Erasure, the compiler erases the generic type information at runtime. The JVM doesn’t know what T actually is, so it cannot allocate memory for it using new T(). If you need to instantiate a type dynamically, you have to pass the Class<T> object into the constructor and use reflection (e.g., clazz.newInstance()).

Q: Can a class have static fields of a generic type T?
A: No. Static fields are shared across all instances of a class. If you create a Box<String> and a Box<Integer>, they both share the exact same static variables in memory. Therefore, a static field cannot be of type T, because T varies from instance to instance.