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)
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With