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?
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.
T
wasn't defined. The order of modifiers and the return type remains the same.
public static <T> T noGood(T t) {
return t;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With