Reputation: 27
I am making a game in which i want to make an array called "Inventory" in which I want to be able to store different types of objects of different classes (such as weapons, bottles, food items )
I want to know how this is possible... arraylist can make only arrays of one type...I tried that too.
thanks in advance.
Upvotes: 0
Views: 1183
Reputation: 4435
Have all your classes of items implement the same interface, "Item". Then make the arraylist of type Item
.
Or, if the items have common data (such as price) you could have them all extend the same class.
Example of extending the same abstract class:
public abstract class Item {
private int value;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
public class Weapon extends Item {
private int damage;
public Weapon(int value, int damage) {
this.setValue(value);
this.damage = damage;
}
}
ArrayList
declaration:
List<Item> inventory = new ArrayList<Item>();
inventory.add(new Weapon(10, 25));
Upvotes: 0
Reputation: 798
You'll have to use an array of a common superclass/interface.
The easiest thing would be to use an array of Object (Object[]), but that includes the risk to add literally anything.
It'd be best if you make an interface that all your objects are going to implement - even if it has to be a tag interface - thus limiting the kind of objects than can be putted there. Of course, if there is common functionalities of those objects (such as attributes like "weights" or methods as "drawObject"), the interface actually has some meaning beyond the tag
Upvotes: 0
Reputation: 155
Let your objects extend a superclass like Item
and make an Item[]
array.
Upvotes: 3