Anatch
Anatch

Reputation: 453

Creating several objects of the same class

I need to create 10 objects from my Variable Class but I'm getting errors.

Here is my code:

for(n=1;n<10;n++){
    variableTab[n]= "variable" +""+n;
    Variable variableTab[n] = new Variable();
    //System.out.println(variableTab[n]);
}

And the errors I have:

I don't know where is the problem because variableTab[] is a String Tab.

Upvotes: 1

Views: 89

Answers (3)

Evan Bechtol
Evan Bechtol

Reputation: 2865

You are trying to assign data to an object that hasn't been created yet. Also, you shouldn't start at index 1. Arrays begin at index 0, so essentially, you are robbing yourself of extra space and making things harder on yourself by doing that. This also means that you are creating 9 objects, not 10.

Use the implementation below.

Variable [] variableTab = new Variable [10];
for(n=0;n<10;n++){
    variableTab[n]= "variable" +""+n;

    //System.out.println(variableTab[n]);
}

Update per comments:

If you are trying to store the name of a object, you need to create a member variable to store that name in.

public class Variable {
   private String name; //This will be used to store the unique name of the object
   //Default constructor for our class
   Variable () {
      name = "";
   }

   //Constructor to initialize object with specific name
   Variable (String name) {
      this.name = name;
   }

   //We need a way to control when and how the name of an object is changed
   public setName (String name) {
       this.name = name;
   }

   //Since our "name" is only modifiable from inside the class, 
   //we need a way to access it from the program
   public String getName () {
      return name;
   }
}


This would be the proper way to setup a class. You can then control the data for each class in a more predictable way, since it is only able to be changed by calling the setName method, and we control how the data is retrieved from other sections of the program by creating the getName method.

Upvotes: 2

Steampunkery
Steampunkery

Reputation: 3874

You're trying to assign values to something that hasn't been created yet! You're code should look like:

for(n=0;n<10;n++){
            Variable variableTab[n] = new Variable();
            variableTab[n]= "variable" +""+n;
            //System.out.println(variableTab[n]);
        }

Basically, you're trying to assign a value to something that doesn't exist yet.

Upvotes: 0

Fiery Phoenix
Fiery Phoenix

Reputation: 1166

You might want to initialize your object first. If it is an array of objects that you're trying to create, do it this way:

Variable[] variableTab = new Variable[n];

Upvotes: 0

Related Questions