If you have a generified class, you can't use the type parameters in static methods since they don't make sense there. For example, consider ArrayList<T>
. You can create a ArrayList<String> stingList = new ArrayList<String>()
and a ArrayList<Integer> integerList = new ArrayList<Integer>
. So now you have to instances of ArrayList, each with their own parameter type, and instance methods that can take advantage of that parameter type like get
. But static methods belong to the class not the instance, so when you call a static method you call it like ArrayList.staticMethod()
NOT stringList.staticMethod()
or integerList.staticMethod()
(you can do that as well, but it doesn't really make sense, since the static method cannot access instance variables, so it does the exact same thing as calling it on the class). But when you call it on the class, the class is just ArrayList, without any type parameters, since the type parameters are only used by instances.
You can however have methods that have their own type parameter, which is independent of the type parameter of the class, like Thomas shows in his answer. So you can then call those method like ExampleClass.<String> staticMethod()
; notice that ExampleClass has no type parameter here, but the method does have it. (you can omit the <String>
in the method call if the compiler can infer it from the parameters used, or the return type: String s = ExampleClass.method2(new ExampleSubclass<String>())
; it usually does a pretty good job at inferring it)