Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method parametrized with one type accepts two types

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?

like image 307
ctomek Avatar asked May 25 '16 21:05

ctomek


1 Answers

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.

like image 170
Sleiman Jneidi Avatar answered Oct 29 '22 14:10

Sleiman Jneidi