PDA

View Full Version : Java: Arrays of class objects?


Annorax
10-27-2005, 02:10 AM
I'm fairly new to Java and coming from a C++ and Qbasic background.

I'm currently making a text RPG which I'm trying to port from C++. In the Java code, I have a class called Item that contains all my item variables and methods. Then, I have another class that is the Game class which is the game itself. Here is where all the items, players, etc.. get initialized. Right now I have something like:

Item club = new Item("club", 1, "A club");

Now, in C++ I used a struct to get an array of item. This made it easy, for example, to tell where items are, since I could just do a for loop and cycle through the entire item list by using item[i].location.

Is there any way to make an array of type Item (or any class in general) in Java? Thank you for any help.

squirellplaying
10-27-2005, 02:45 AM
Yup, just do
Items[] clubs = new Items[numberOfItems];

Then get the value you want by calling the methods associated with that object. So clubs[1].getName();

Annorax
10-28-2005, 01:29 AM
Thank you for the help.

Is it possible to use the class constructor when declaring the class as an array? For example, I can now define:

Item club = new Item("Club", 1, "This is a club.")

Because when I manually do something like this:

items[0].name = "club";

I get a NullPointer, since, naturally it is empty.

tsclan
10-28-2005, 11:33 AM
items[0]= club;

brad211987
10-28-2005, 05:41 PM
Is it possible to use the class constructor when declaring the class as an array? For example, I can now define:

Item club = new Item("Club", 1, "This is a club.")

Because when I manually do something like this:

items[0].name = "club";

I get a NullPointer, since, naturally it is empty.

name, if I understand correctly should be a private instance variable in your item class ie: private String name;

so the classes constructor should initialize that, and u can call it from your other class using:
items[x] = new Item(name,value,text).


this:
Items[] clubs = new Items[numberOfItems];

creates the array of items, but does not actually create the item objects, it reserves space for item objects. so the next step is to call the constructor for each index of the array like I said above. Hope this helps.

Annorax
10-30-2005, 01:01 AM
Thank you all, this has been most helpful. :)