Richard Quasla
Richard Quasla

Reputation: 27

storing objects of different types in one array to make an array of objects

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

Answers (3)

forgivenson
forgivenson

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

dtortola
dtortola

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

Mystery
Mystery

Reputation: 155

Let your objects extend a superclass like Item and make an Item[] array.

Upvotes: 3

Related Questions