Does Java shadow type parameters? I am finding it hard to test for myself because Java generics do not get reified at run time.
For example, given this code:
public class NestedGeneric<T> {
private InnerGeneric<T> innerGenericInstance;
private static class InnerGeneric<T> {
public T innerGenericField;
}
NestedGeneric() {
innerGenericInstance = new InnerGeneric<T>();
}
}
Both the below statements compile fine:
NestedGeneric<Integer> test1 = new NestedGeneric<Integer>();
NestedGeneric.InnerGeneric<String> test2 = new NestedGeneric.InnerGeneric<String>();
When the NestedGeneric
is passed a type parameter and its constructor called, what is T
? Is it always going to be the same as the type parameter passed to nestedGeneric
?
In other words, can an outer classes type parameters be passed to an inner classes generic type declarations?
No. There is no relationship (like inheritance or as a field) between the outer and the inner static class. You can create an object of the inner static class without any dependency on the outer class like in your example:
However when you use an instance of the inner class as a field the generic type is derived from the outer class:
A third variation would be to define the inner class as a field (non-static):
which will now get the type from the outer class since its a member variable.
As pointed out in the comment defining both inner static & outer class with the type will just confuse the reader (and yourself at a later point in time). It should be declared with a different generic like