user6893764
user6893764

Reputation:

Java Arrays and constructors

I am trying to make an object that has int in parameters, thats sends the value to another class, sets the value of the int to a private int in a constructor of another class and using the private int to set the size of an array, but i dosnt work... Does anyone know why? Below is an example of what i mean, i want to set the arrays size to 10.

main class: Car bmw = new Car(10);

Car class: public Car (int x)
              { y = x;}
private int y;
private String[] carArray= new String[y];

Upvotes: 0

Views: 260

Answers (3)

Thomas
Thomas

Reputation: 88757

The problem with your code: private String[] carArray= new String[y]; will be executed before the constuctor body. In your case y will still be 0 (that's the default for primitive fields) which results in an array of length 0 being created.

Thus you'll have to do it like that:

public Car (int x) { 
  y = x;
  carArray= new String[y];
}

Basically the call order is:

  • super class' initializer block/constructor (if there are any)
  • this class' initializer block
  • this class' constructor

Example: assume we have class Car extends Vehicle.

If you call new Car(10) the call order might look like this (assuming there are no calls to other constructors:

  • Vehicle initializer block
  • Vehicle constructor
  • Car initializer block
  • Car constructor

An "initializer block" consists of everything that's in the class body but not part of a method (there actually are 2 initializer blocks: a static one and an instance one, the static one can be identified by the static keyword).

Upvotes: 3

Luka Jacobowitz
Luka Jacobowitz

Reputation: 23532

You have to initialize the Array inside your constructor:

public Car (int x) { 
    y = x;
    carArray= new String[x];
}

Upvotes: 0

Amer Qarabsa
Amer Qarabsa

Reputation: 6574

instead initialize the array in the constructor

   main class: Car bmw = new Car(10);
           private int y;
         private String[] carArray=null;
     Car class: public Car (int x)
          { y = x;
           carArray= new String[y];
}

Upvotes: 0

Related Questions