Micheal
Micheal

Reputation: 1

Why every time I create a new element of an object array the element created before takes the same properties as the new element

I've created a class called Tile, which renders an image to the screen by giving it an image, x posit., y posit., width, height and graphic object. Here's the code of that class:

package tile;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import image.Assets;

public class Tile {

public static int x, y, width, height;
public static BufferedImage image;
Graphics graf;
public static int id;



public Tile(int tx, int ty, int twidth, int theight, Graphics g, BufferedImage timage, int tId)
{
this.width = twidth;
this.x = tx;
this.y = ty;
this.image = timage;
this.graf = g;
this.height = theight;
this.id = tId;

}

 public void render()
{ 

this.graf.drawImage(this.image, this.x, this.y, this.width, this.height, null);

}
//And then here are the getters and setters methods...

I want to create an array of object Tile where everyone element of this array has different properties. So I wrote this code in another class:

...
Tile []t = new Tile[216];
for(int i = 0; i < 100; i++)
{
 t[i] = new Tile(x, y, width, height, graphic, image, id)
 t[i].render();
}
...

but every time it creates a new Tile object in this array, the other created before this one take the same properties as the new created. Where's my error/s? Thanks for the answers and excuse me for this bad English.

Upvotes: 0

Views: 43

Answers (1)

Philipp Cla&#223;en
Philipp Cla&#223;en

Reputation: 43969

Do not use static variables. Instead of writing

public static int x, y, width, height;
public static BufferedImage image;
public static int id;

try

public int x, y, width, height;
public BufferedImage image;
public int id;

Static Variables are global, that means they are shared by all instances. That is why properties are overwritten when you create new instances.

Upvotes: 3

Related Questions