Type mismatch Error : Cannont convert from ArrayList<SubClass1> to List<SuperClass>
It seems you're trying to create a list that only contains objects from the particular subclass. In this case you just need the generics to play nice at compile time. (Generics are erased at runtime :) )
class AClass<T extends SuperClass> {
List<T> list;
public AClass(){
list = new ArrayList<T>();
}
void addObjects(T obj){
list.add(obj);
}
}
You should use a bounded wildcard in your ArrayList declaration:
class AClass{
List<? extends SuperClass> list;
public AClass(boolean b){
if(b)
list = new ArrayList<SubClass1>();
else
list = new ArrayList<SubClass2>();
}
}
}
The type of the parameter to list.add() is ? extends
SuperClass-- an unknown subtype of SuperClass. Since we don't know what type it is, we don't know if it is a supertype. it might or might not be such a supertype, so it isn't safe to pass a SubClass1 or SubClass2 there.