Skip to content

generic-methods-java

Generic Methods in Java allow methods to introduce their own type parameters, independent of the type parameters defined by the class or interface they belong to^[600-developer__java__java-base__Generics.md].

Overview

While Java supports [[generics]] across classes, interfaces, and methods, generic methods specifically enable a method to define its own type variables. This allows the method's logic to change or adapt based on specific types, even if the containing class is not generic or uses a different type parameter^[600-developer__java__java-base__Generics.md].

Syntax and Implementation

A generic method is declared by placing a type parameter section inside angle brackets <> before the method's return type^[600-developer__java__java-base__Generics.md].

The following example demonstrates a class Generic that defines a type parameter T, and a method showKeyName that defines its own independent type parameter U:

class Generic<T> {
    T key;

    public T getKey() {
        return key;
    }

    // U is a type parameter specific to this method
    public <U extends Number> U showKeyName(Generic<U> container) {
        System.out.println("container key :" + container.getKey());
        U test = container.getKey();
        return test;
    }
}
^[600-developer__java__java-base__Generics.md]

In this example, U is bounded by extends Number, restricting the types that can be passed to the method^[600-developer__java__java-base__Generics.md].

  • [[generics-java]]

Sources