Generics

Generics in Java allow you to define classes, interfaces, and methods with type parameters. This tutorial will teach you how to use generics.

Creating Generic Classes

To create a generic class, use the following syntax:


class GenericClass {
    private T value;
    
    public void setValue(T value) {
        this.value = value;
    }
    
    public T getValue() {
        return value;
    }
}

public class Main {
    public static void main(String[] args) {
        GenericClass stringInstance = new GenericClass<>();
        stringInstance.setValue("Hello");
        System.out.println(stringInstance.getValue());
        
        GenericClass integerInstance = new GenericClass<>();
        integerInstance.setValue(123);
        System.out.println(integerInstance.getValue());
    }
}
      

Creating Generic Methods

To create a generic method, use the following syntax:


public class Main {
    public static  void printArray(T[] array) {
        for (T element : array) {
            System.out.println(element);
        }
    }
    
    public static void main(String[] args) {
        String[] stringArray = {"Hello", "World"};
        Integer[] intArray = {1, 2, 3};
        
        printArray(stringArray);
        printArray(intArray);
    }
}
      

Bounded Type Parameters

You can use bounded type parameters to restrict the types that can be used with generics:


class GenericClass {
    private T value;
    
    public void setValue(T value) {
        this.value = value;
    }
    
    public T getValue() {
        return value;
    }
}

public class Main {
    public static void main(String[] args) {
        GenericClass integerInstance = new GenericClass<>();
        integerInstance.setValue(123);
        System.out.println(integerInstance.getValue());
        
        // The following line will cause a compile-time error
        // GenericClass stringInstance = new GenericClass<>();
    }
}
      

In this example, the GenericClass is restricted to types that extend Number.

Continue exploring our intermediate tutorials to learn more about Java programming.

Scroll to Top