Probably I am missing something and maybe my assumptions were wrong, but I thought that when I declare parametrized method with type T then no matter how much variables there are with that type it is still the same type. But I see that this compiles and it oposses my view.
static <T> void f(T a, T b) { }
public static void main(String[] args) {
f(Integer.MIN_VALUE, "...");
}
So if my method is parametrized with one type and I am using that one type in two paramteres why does it allow me to send two objects with two totally different types? I guess it comes down to treating T as Object?
Although Integer and String are two different types, they still share a common super-type. Serializable.
To verify this, lets return T,
static <T> T f(T a, T b) {
return null;
}
Serializable s = f(Integer.MIN_VALUE, "..."); // compiles
The compiler will resolve (or infer, not sure about the technical term) to the most specific type. For example,
Number number = f(Integer.MAX_VALUE, BigDecimal.ONE);
Now, the type resolved is Number because both types are subtypes of Number,as well as Serializable, as well as Object of course.
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