Reputation: 353
So I have a class, called Hero:
public class Hero {
public static int x;
public static int y;
Hero() {
x=0;
y=0;
}
Hero(int x, int y) {
this.x = x;
this.y = y;
}
public Hero(Hero h) {
this(h.x, h.y);
}
}
I made an array of Heros. However, when I change hero[0], hero[1] and all the others change as well. Also, when I make another hero, like this:
Hero guy = new Hero();
and change his x like this:
guy.x = 4;
suddenly all Hero objects I have created have an x value of 4.
Another example within the same project:
import javax.swing.JMenuItem;
public class bonusItem extends JMenuItem{
public static int X;
public static int Y;
bonusItem(String s, int x, int y) {
super(s);
X=x;
Y=y;
}
public void setCols(int cols) {
X = cols;
}
public void setRows(int rows) {
Y = rows;
}
public int getCols() {
return X;
}
public int getRows() {
return Y;
}
}
If I do this (after making the array, of course):
bonus[1].setRows(9);
bonus[1].setCols(9);
bonus[0].setRows(8);
bonus[0].setCols(8);
for(int i=0; i<bonusCount; i++)
System.out.println("Bonus " + i + " has " +
bonus[i].getRows() + " rows and "
+ bonus[i].getCols() + " columns.");
The output is: Bonus 0 has 8 rows and 8 columns. Bonus 1 has 8 rows and 8 columns.
I'd really just like to have an array of discrete objects, rather than whatever's going on here. Any help would be appreciated. Thanks!
Upvotes: 3
Views: 89
Reputation: 46900
This question is a classic explanation of the static
phenomena.
public static int x;
public static int y;
Using static
how do you even expect that you can have different values for different objects?
static
members are for the class itself, they are not tied to any single object. Hence a static
will keep the same value even if you have hundreds of objects.
From Documentation
Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.
You should be declaring them like
private int x; // or public like you did
private int y;
Upvotes: 6