public static <T> T foo(T x, T x2) {
return (T) (x + " " + x2);
}
public static void main(String args[]) {
System.out.println(foo(33, "232"));
}
I know T gets to be of the type that is passed in the parameter. But here there are two types. Which one of them is T?
and why the compiler doesn't force me to have the parameters of same type when I call foo?
A generic type is a class or interface that is parameterized over types, meaning that a type can be assigned by performing generic type invocation, which will replace the generic type with the assigned concrete type.
Generics is a concept in Java where you can enable a class, interface and, method, accept all (reference) types as parameters. In other words it is the concept which enables the users to choose the reference type that a method, constructor of a class accepts, dynamically.
Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.
String is a subtype of Object , because the String class is a subclass of the Object class. int is not a subtype of Object , because none of Java's primitive types are subtypes of any reference type.
It's legal because Integer
and String
have a common base type. T
can be Object
, so foo(T, T)
will accept any two objects. 32
can be autoboxed to an Integer
, which is a kind of Object
. "232"
is a String
, which is a kind of Object
.
(As pointed out by comments, for Integer
and String
, there is a closer common base-type, Serializable
; but the principle is the same whichever base type the compiler resolves T
to.)
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