I have outer generic class which has some inner class, for which I'd like to use the generic type of outer class.
However, I don't understand how to use generic parameters correctly.
Example:
class Outer<E extends CharSequence>{
class Inner extends ArrayList<E>{
}
void func() {
ArrayList<CharSequence> al = new ArrayList<CharSequence>();
al.add("abc"); // OK
CharSequence a = al.get(0); // OK
Inner in = new Inner();
in.add("abc"); // Error: The method add(E) in the type ArrayList<E> is not applicable for the arguments (String)
CharSequence b = in.get(0); // OK
}
}
How can I declare inner class to use same generic type of outer class? Thanks
EDIT + Solution:
Finally I achieved what I wanted, here's example result:
abstract class MyGenericClass<E extends CharSequence>{
class TheList extends ArrayList<E>{};
TheList list = new TheList();
}
final class ClassInstance extends MyGenericClass<String>{
};
public class Main{
public static void main(String[] args){
ClassInstance c = new ClassInstance();
c.list.add("abc");
String s = c.list.get(0);
}
}
My requirement was to have generic class, and also have generic container in it, which would use same type parameter as its parent class.
Note: CharSequence/String are example parameters of use, my real usage is different.