I have a class B which extends A. A stores a list of AItem and B stores a list of BItem
In 'A' I have an ArrayList which uses [? extends AItem] .
I assume this means that I can use this ArrayList for objects of any type that extends AItem.
So in my B class I have a method add(..) which adds a BItem to the items.
I assumed this would work because the items arrayList can hold a list of any object that extends from AItem.
import java.util.ArrayList;
class A {
public ArrayList<? extends AItem> items;
}
public class B extends A{
public void add(BItem i) {
this.items.add(i); //compile error here
}
}
//items :
class AItem {}
class BItem extends AItem{}
How would I get this to work?
My compile error looks like this :
The method add(capture#2-of ? extends AItem) in the type ArrayList is not applicable for the arguments (BItem)
You probably don't need to use generics here. Having the list of type AItem in class A should be fine (I would also declare it of type List instead of ArrayList for best practices):
class A {
public List<AItem> items;
}
class B extends A {
public void add(BItem i) {
this.items.add(i);
}
}
The problem with ? extends AItem is that the compiler cannot guarantee that the actual type of the elements is AItem or BItem. It could be another subclass CItem in which case the type safety is broken.
There is another approach to designing the class hierarchy with generics, in which you set the type parameter in the parent class and set it to the appropriate subclass (BItem) in the extended class B:
class A<T extends AItem> {
public ArrayList<T> items;
}
class B extends A<BItem>{
public void add(BItem i) {
this.items.add(i);
}
}
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