I am not able to understand how T is taking Integer and String. As here in display function T is dealing with both Integer and String. How this code is working?
class firstBase {
<T> void display(T give_num, T give_String) {
System.out.println("The given number is = "
+ give_num + " The given String is = " + give_String);
System.out.println("The class of given number is = "
+ give_num.getClass() +
" The class of given_String is = "+give_String.getClass());
}
}
public class testanonymous {
public static void main(String[] args) {
firstBase fb = new firstBase();
fb.display(100, "xyz");
}
}
You're invoking the raw form of the method, which is basically equal to
void display(Object give_num, Object give_String)
Here, both of the arguments you provide fit, because 100
is autoboxed to Integer
(which is a subclass of Object
) and "xyz" is a String
(which is a subclass of Object
)
To use Generics correctly, you have to do:
fb.<String>display(100, "xyz");
or
fb.<Integer>display(100, "xyz");
In both cases, you'll note that the code doesn't compile, because the compiler will be aware of your intent to replace T
with Integer
/String
at Runtime, but the parameter types are not of the same provided type.
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