Apologies for the convoluted question, but I can't figure out an easier way to ask it. I am currently experimenting with generics and have run into something I cannot wrap my head around. I have a generic class with type parameter T and it has a generic inner class with type parameter E. However, the inner class' constructor requires a T.
If I instantiate the outer class with, say, Outer<String> and instantiate the inner class with <Integer>, and call its constructor using an integer, there is no problem. This does not make any sense to me, as in this case the constructor should only work with a String as is set in the Outer type parameter. Why is this the case?
If I create a method in the inner class that requires a T, though, The method method(T) in the type Outer<T>.InnerGeneric<Integer> is not applicable for the arguments (int) which does make sense to me. How come this does not happen with the constructor method?
Here is a snippet of my code:
public class Outer<T> {
class InnerGeneric<E> {
InnerGeneric(T t) {
//do something
}
void method(T t) {
//do something
}
}
class Inner {
}
Outer(T t) {
InnerGeneric<T> inner1 = new InnerGeneric<>(t);
InnerGeneric<Integer> inner2 = new InnerGeneric<>(1); //i do not get any error here,
and the code can run just
fine with this, why???
inner2.method(t);
inner2.method(1); //get a compilation error here, this makes sense to me
}
public static void main(String[] args) {
Outer<String> outer = new Outer<>("Any string");
}
}
EDIT: I am using Eclipse, not sure about what that means in terms of what version of javac, as I am still fairly new to it all