Here is my class Structure, and where I am getting error
class SuperClass{
//variables
}
class SubClass1 extends SuperClass{
//variables
}
class SubClass2 extends SuperClass{
//variables
}
class AClass{
List<SuperClass> list;
public AClass(boolean b){
if(b)
list = new ArrayList<SubClass1>();//getting error here
else
list = new ArrayList<SubClass2>();//and here
}
void addObjects(SuperClass obj){
list.add(obj);
}
}
How can I solve this? Should I change my design ? How?
ADDITION:
When I changed
`List<SuperClass> list;`
to
List<? extends SuperClass> list;
I am not getting the previous error but I am getting another error while adding objects,
The method add(capture#2-of ? extends SuperClass) in the type List<capture#2-of ? extends SuperClass> is not applicable for the arguments (SuperClass)
You should use a bounded wildcard in your ArrayList declaration:
The
?
is a wildcard and defines an unknown type. But by using a bounded wildcard you can assure that it is an unknown subtype of SuperClass.For further information about wildcards see here.
Concerning you're other problem:
The type of the parameter to list.add() is ? extends
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 :) )