Reputation:
In Java, why does an untyped invocation of a constructor of parameterised type provoke a compiler warning? Why is it okay to do similar thing with a static method? For example:
class Test<T> {
Test() {}
static <T> Test<T> create() {
return new Test<T>();
}
@SuppressWarnings("unused")
public static void main(String[] args) {
Test<String> warning = new Test(); // compiler warning - why?
Test<String> okay = Test.create(); // no warning here - why?
Test<String> okay2 = Test.<String>create(); // why doesn't it need this?
}
}
Upvotes: 0
Views: 329
Reputation: 567
Java does type inference on methods (which is why line 2 works and line 3 is not necessary), but not on constructors (which is why line 1 gives a warning).
It would be nice if Java did type inference on constructors too, but as of Java 6 it does not.
Upvotes: 1
Reputation: 545558
Because you assign an untyped instance to a typed variable. Your three cases:
new Test<String>()
would be correct.new Test<T>()
(instead of just new Test()
).Upvotes: 8