If I have a class Foo:
public class Foo<T> {
public Foo(T t) {
//do something
}
public static <E> void bar(E e) {
//do something
}
}
Why does Foo.bar("String"); infer that E is a String (and therefore not throw a compiler warning) but new Foo("String"); not infer that T is a String?
Because the constructor can be considered a special instance method, it is not typed – it gets its type from the class name (with a type parameter),eg
Foo<String>. ie the constructor is not defined as:nor can it be. Doing so would hide the generic type of the class (and you’ll get a warning)
The static method however is typed. FYI, the generic-parameter-less call, once the type is inferred, is equivalent to: