I want to use a generic class inside a nested static interface. My objective is to do something like this:
public class MyClass{
private MyInter
It's not redundant. With a static interface:
MyClass.MyInterface<String> myInstance;
and with a non-static innter class (an interface is always static):
MyClass<String>.MyInterface myInstance;
A more real world example:
Map<String, Integer> map = ...;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
...
}
The static approach has the advantage that you can import the nested type, and still specify the type parameters:
class ClassWithAReallyLongName<T> {
static interface Entry<T> {
}
}
and
import my.package.ClassWithAReallyLongName.Entry;
class Foo {
Entry<String> bar;
}
though one should use that idiom with caution as to not confuse the reader.
A static nested class or nested interface (which is always static, by the way) has no relation to its outer class (or interface) apart from namespace nesting and access to private variables.
So, the type parameter of the outer class is not available inside the nested interface in your case, you should define it again. To avoid confusion, I recommend using a different name for this inner parameter.
(As an example in the standard API, look for the interface Map.Entry<K,V>
, nested inside the interface Map<K,V>
, yet has no access to its type parameters and needs to declare them again.)