Course contentsShow
← Java
Lesson 874 of 2,87021. Generics FundamentalsFree lesson

Creating Instances of Generic Classes

Learn how to instantiate generic classes using type arguments and understand the basic syntax.

Creating Instances of Generic Classes

What you'll learn: How to use angle brackets and type arguments to create objects from generic classes you've defined.


The Core Idea

Once you've declared a generic class (like Box<T>), you need to tell Java what actual type will replace that type parameter when you create an instance. This is called instantiation with type arguments. You specify the concrete type inside angle brackets on the right side of the assignment.

Think of it like ordering a custom container: the factory (your generic class) can make boxes for any type, but when you place your order (instantiate), you must specify exactly what goes inside—Box<String>, Box<Integer>, etc.

Basic Syntax

// The generic class declaration (you've learned this)
class Box<T> {
    private T item;
    
    public void setItem(T item) {
        this.item = item;
    }
    
    public T getItem() {
        return item;
    }
}

// Creating instances with type arguments
Box<String> stringBox = new Box<String>();
Box<Integer> intBox = new Box<Integer>();

Notice how <String> and <Integer> replace the generic T in each instance. Each box now knows its specific type at compile time.

Multiple Type Parameters

class Pair<K, V> {
    private K key;
    private V value;
    // constructor and methods...
}

// Instantiate with two type arguments
Pair<String, Integer> pair = new Pair<String, Integer>();

You provide type arguments in the same order as the type parameters were declared.

Key Takeaway: To create an instance of a generic class, specify the concrete type arguments in angle brackets (e.g., new Box<String>()), replacing the generic type parameters with actual types.