user3308874
user3308874

Reputation: 3

Array overwriting all other values when a new one is added

I have been having an issue when adding objects to an array. It seems that every single time I add a new WoodFloor object to the array, it overwrites all of the other values of the array. Here's my code:

package code;

public class Main {

private static Block[] blocks = new Block[12];

public static void main(String[] args) {
    for(int i = 0; i < 12; i++) {
        blocks[i] = new WoodFloor(i * 10, i * 20);
    }
  }
}



package code;

public class Block {

protected static int x, y;

public Block(int x, int y) {
    this.x = x;
    this.y = y;
}

public int getX() {
    return x;
}

public int getY() {
    return y;
}

}


package code;

public final class WoodFloor extends Block {

public WoodFloor(int x, int y) {
    super(x, y);
}

}

Upvotes: 0

Views: 87

Answers (4)

Sky
Sky

Reputation: 3360

I'm suspecting it's the 'static' keyword for x and y.

Upvotes: 0

user3400021
user3400021

Reputation: 11

Static makes the variable available at the class lever so an instance is not needed to access it. Here effectively resets it to its original value each time rather than moving to the next array position and forgets the old array.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726519

Your program produces 12 different objects, but they all reference the same pair of x and y. The problem is on this line:

protected static int x, y;
//        ^^^^^^

When you make a field static, you are saying that the value of this field is going to be the same in every single object of the class. This is definitely not what you are trying to achieve here: you need each WoodFloor to have its own x and y. For that, you use instance fields (i.e. fields declared without static).

Upvotes: 2

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

Don't use static modifier for class fields that need to be different for each instance. The static modifier makes the field a class field, one that is effectively shared by all instances, and this is not what you want.

So change this:

protected static int x, y;

to this:

protected int x, y;

Upvotes: 2

Related Questions