sorry, this question might be very simple but I didn't find the answer in the internet.
public class Main {
public static void main(String[] args) {
int a = 1;
double b=2;
max(a,b);
}
public static <E> void max(E first , E second)
{
System.out.println(first);
System.out.println(second);
}}
when we pas the first parameter an integer then E is set to Integer and then we pass a double to it. we should get a compile error. (because E is Integer) but the program runs correctly and the output is
1
2.0
so what is my mistake?
If you hover over the method call in Eclipse, you'll see:
<? extends Number> void Main.max(? extends Number first, ? extends Number second)
i.e. the compiler infers the type of the generic type parameter as something that extends Number. Therefore, both Integer and Double, which extend Number are valid arguments for the max method.
If you print the types of the arguments passed to the max method:
public static <E> void max(E first , E second)
{
System.out.println(first);
System.out.println(second);
System.out.println (first.getClass ());
System.out.println (second.getClass ());
}
you'll see that an Integer and a Double were passed to the method:
1
2.0
class java.lang.Integer
class java.lang.Double
Java's type inference algorithm finds the most specific type that your arguments share. In this case, it should be Number.
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