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

Type Parameters in Fields, Methods, and Constructors

Use type parameters to declare field types, return types, and parameter types.

Type Parameters in Fields, Methods, and Constructors

What you'll learn: How to use type parameters throughout your generic class—in fields, method signatures, and constructor parameters.


The Core Idea

Once you've declared a type parameter (like T) at the class level, you can use it anywhere inside that class where you'd normally specify a type. This means your fields can store values of type T, your methods can accept or return T, and your constructors can take parameters of type T. The actual type gets "filled in" when someone instantiates your class.

Think of the type parameter as a placeholder that gets replaced with a real type (like String or Integer) at instantiation time. Everywhere you wrote T inside your class becomes that concrete type.


Using Type Parameters

In Fields:

private T item;  // The field type matches the type parameter

In Constructors:

public Box(T item) {  // Constructor parameter uses T
    this.item = item;
}

In Methods (return type and parameters):

public T getItem() {  // Return type is T
    return item;
}

public void setItem(T newItem) {  // Parameter type is T
    this.item = newItem;
}

When you create a Box<String>, every T becomes String. When you create a Box<Integer>, every T becomes Integer. The compiler ensures type safety throughout.


Complete Example

public class Box<T> {
    private T item;  // Field

    public Box(T item) {  // Constructor
        this.item = item;
    }

    public T getItem() {  // Return type
        return item;
    }

    public void setItem(T newItem) {  // Parameter type
        this.item = newItem;
    }
}

Key Takeaway: Type parameters declared at the class level can be used as field types, return types, and parameter types throughout the class, providing consistent type safety everywhere.