I want to have a collection of subclass objects but with my generic type implementation as it is now gives an error at allItems.add(item); because allItems does not hold Item types. So how can I change the below code not give an error?
public class ItemManager {
public static Collection<? extends Item> allItems;
...
public static boolean addItem(Item item){
return allItems.add(item);
}
}
A new item might be added as:
itemManager.add(new Bomb());
Is there a way to change addItem to:
public static boolean addItem([all subclasses of Item] item) { ... }
or maybe change allItems so it can accept receiving an Item and a subclass of Item?
The collection should be declared as
Collection<Item>.Collection<? extends Item>means: a collection of some unknown class which is or extends Item. You can’t add anything to such a collection, since you don’t know the type of objects it holds.