Java Generic Method Tutorial

  • Post author:
  • Post category:Java

In this section, we will learn what the generic method is and how it works in Java.

Note: we’re assuming you’re already familiar with generic classes.

Generic Methods in Non-Generic classes

Other than declaring type parameters in a class declaration, we can create a non-generic class that has one or more generic methods.

Basically, we can set type parameters that can be used for parameters in a method declaration. They are specified in angle brackets before the return type of the method.

Again, the class that contains the generic method declaration does not have to be a generic class.

Example: Creating Generic Methods in Non-Generic classes

public class Simple {

    public static <T>  void check(T t){
        System.out.println("The value of the t is: "+t);
    }
    public static void main(String[] args) {
       Simple.<String>check("Hi");
    }
    
}

Output:

The value of the t is: Hi

Here the `check` method is generic static one and so via the name of the class we accessed the method.

Note: after the dot `.` operator, we use the angle brackets `<>` to set the actual data type of the method’s type parameter.

Generic non-static methods in Java example:

The same method in this example, if it was a non-static method, we could create an object from the class and run the same technique via the object:

public class Simple {

    public <T extends Number>  void check(T t){
        System.out.println("The value of the t is: "+t);
    }
    public static void main(String[] args) {
       Simple simple = new Simple();
       simple.<Integer>check(10);
    }
}

Output:

The value of the t is: 10

Example: Calling a generic method without angle brackets

The compiler is capable of inferring the data type automatically and so we can simply remove the angle brackets when calling the target method.

public class Simple {

    public <T extends Number>  void check(T t){
        System.out.println("The value of the t is: "+t);
    }
    public static void main(String[] args) {
       Simple simple = new Simple();
       simple.check(10);
    }
}

Output: The value of the t is: 10

More to Readable

Java wildcard

Leave a Reply