Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why type parameter required before return type for static generic methods

The following noGood method gives a compilation error because it omits the formal type parameter immediately before the return type T.

public static T noGood(T t) {
  return t;
}

Could somebody please help me understand that why is it required for a static generic method to have a type parameter before the return type? Is it not required for a non-static method?

like image 685
skip Avatar asked Sep 10 '18 14:09

skip


2 Answers

The type parameter (T) is declared when you instantiate the class. Thus, instance methods don't need a type argument, since it's defined by the instance.

static methods, on the other hand, don't belong to an instance - they belong to the class. Since there's no instance to get the type information from, it must be specified for the method itself.

like image 105
Mureinik Avatar answered Oct 12 '22 23:10

Mureinik


T wasn't defined. The order of modifiers and the return type remains the same.

public static <T> T noGood(T t) {
    return t;
}
like image 35
Andrew Tobilko Avatar answered Oct 12 '22 22:10

Andrew Tobilko