Search code examples
javagenericsmethodsstaticgeneric-method

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?


Solution

  • 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.