开发者

object array assignment problem

I have a problem where each element of my array seem to be reassigned.

class Car {
    private static int nom = 0;
    private static String whee = "";
  开发者_开发问答  public void setCar(int r, String s) {
        this.nom = r;
        this.whee = s;
    }
}

class Rawr {
    private Car[] jar = new Car[3];

    public Mar() {
        jar[0] = new Car();
        jar[1] = new Car();
        jar[2] = new Car();
        jar[0].setCar(2, "yar");
        jar[1].setCar(3, "tar");
        jar[2].setCar(4, "sars");
    }
}

If I printed it like jar[0].nom + jar[0].whee + jar[1].nom + jar[2].whee + jar[3].whee, the output would be

4 sars 4 sars sars


It's because your variables are static i.e. they belong to the class, rather than to an instance. Take a look at Java Tutorials | Understanding Instance and Class Members for more information about what this means.

You should remove the static keyword, so that they become instance variables.


Change

private static int nom = 0;
private static String whee = "";

to

private int nom = 0;
private String whee = "";

static means the variable is shared by all instances. (The fact you can use this to refer to static variables is a Java oddity.)


Your nom and whee fields are static. This means that they are tied to the class, and not to the object (instance) of the class.

Thus, when you assign a new value to this.nom, in reality, you assign a the value to Car.nom. The compiler allows referring to static variables through an object, but it's very bad practice. You should always refer to static fields by their class : Car.nom, Car.whee. This makes it clear that the nom and whee are static, and thus shared by all instances of the class. In this case, these fields should not be static : each Car instance has its own name and whee (whatever it might be).


A better way to structure your code is as follows.

class Car {
    private final int nom;
    private final String whee;
    public Car(int nom, String whee) {
        this.nom = nom;
        this.whee = whee;
    }
    public String toString() { return num + " " + whee; }
}

class Rawr {
    private final Car[] jar = {new Car(2, "yar"), new Car(3, "tar"), new Car(4, "sars")};
    public String toString() {
        return Arrays.toString(jar);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜