Maybe can somebody help me understand better how generics work in Java.
I have "problems" in understanding this sample of code:
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}
class A<T> {
T t;
void set(T t) {
this.t = t;
}
T get() {
return t;
}
}
public class Test {
public static <T> void print1(A<? extends Animal> obj) {
obj.set(new Dog()); //Line 22
System.out.println(obj.get().getClass());
}
public static <T> void print2(A<? super Dog> obj) {
obj.set(new Dog()); //Line 27
System.out.println(obj.get().getClass());
}
public static void main(String[] args) {
A<Dog> obj = new A<>();
print1(obj); //Line 33
print2(obj); //Line 34
}
}
Line 22 does not compile because the compiler "s not sure about the data that would come at runtime". If I have understood right how generics work on line 22 we could pass : A <Animal>
, A <Dog>
and A <Cat>
.
In short words Animal
class or any other class that extents Animal
.
Now if we look at print2 (public static <T> void print2(A<? super Dog> obj)
) we have super, and this means that we can pass Animal
or any superclass of Animal
.
Now if the first method does not compile because the compiler does not know what type will be passed at runtime should this also be the case for the second method where super
is used.
For the second method, we can pass A<Animal>
and A<Object>
.
What I am missing here?
Thanks