I'm just getting in touch with generics and I have several doubts. The first is that I don't understand what exactly this code does and how it can compile:
package exercise;
public class GenereicExample<T> {
public T var = (T) "hola";
public static void main(String[] args) {
GenereicExample<Integer> cadena = new GenereicExample<Integer>();
System.out.println(cadena.var);
}
}
I'm just doing tests to see how they work and how generics are used, I think that code doesn't make any sense to do it like that, but it's just to learn.
Let's see, from what I understand when declaring GenericExample as Integer, the variable "var" is supposed to be a numeric variable and it should fail, right? Well, it runs and shows me hello, so either I haven't done something right or I don't fully understand how generics work. It may also be that the key is in this line:
public T var = (T) "hola";
I don't understand exactly what kind of casting is being done there.
Thank you!
Generics are an aid to the developer during code writing and compilation, but they don't exist at runtime. So something like
At runtime it transforms to:
In your case, since the type cannot exist at runtime and you haven't put a constraint on the generic type, your code becomes something like:
That will not give any execution error.