SyntaxStudy
Sign Up
Java Generic Classes and Methods
Java Beginner 1 min read

Generic Classes and Methods

Generics allow you to write classes, interfaces, and methods that operate on a type parameter rather than a concrete type. This provides compile-time type safety — the compiler catches type mismatches before your program runs — and eliminates the need for explicit casting. The type parameter is declared between angle brackets and can be any valid identifier, though T (type), E (element), K (key), and V (value) are conventional names. A generic class is declared by appending the type parameter to the class name: class Box. Inside the class, T can be used anywhere a type is expected, such as field declarations, method return types, and parameter types. When you instantiate a generic class, you provide the concrete type: Box or Box. Java uses type erasure, meaning the generic type information exists only at compile time and is removed at runtime. Generic methods allow individual methods to be generic independently of their class. You declare the type parameter before the return type: public T identity(T value). Generic methods are especially useful in utility classes where you want a single method to work with any type. The compiler infers the type argument from the method arguments, so you rarely need to specify it explicitly.
Example
// Generic class
class Pair<A, B> {
    private final A first;
    private final B second;

    public Pair(A first, B second) {
        this.first  = first;
        this.second = second;
    }

    public A getFirst()  { return first;  }
    public B getSecond() { return second; }

    @Override
    public String toString() {
        return "(" + first + ", " + second + ")";
    }
}

// Generic method
class Utils {
    public static <T> T last(java.util.List<T> list) {
        if (list.isEmpty()) throw new java.util.NoSuchElementException();
        return list.get(list.size() - 1);
    }

    public static <T extends Comparable<T>> T max(T a, T b) {
        return a.compareTo(b) >= 0 ? a : b;
    }
}

public class GenericsDemo {
    public static void main(String[] args) {
        Pair<String, Integer> p = new Pair<>("Age", 30);
        System.out.println("Pair: " + p);
        System.out.println("First: " + p.getFirst());

        java.util.List<Integer> nums = java.util.List.of(1, 2, 3, 9, 4);
        System.out.println("Last: "  + Utils.last(nums));
        System.out.println("Max(7,3): " + Utils.max(7, 3));
        System.out.println("Max(apple,zebra): " + Utils.max("apple", "zebra"));
    }
}