对象数组赋值问题
我有一个问题,数组的每个元素似乎都被重新分配。
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");
}
}
如果我像 jar[0].nom + jar[0].whee + jar[1].nom + jar[2].whee + jar[3].whee
那样打印它,输出将是
4 sars 4 sars sars
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是因为您的变量是静态的,即它们属于类,而不是实例。查看 Java 教程 |了解实例和类成员以获取有关其含义的更多信息。
您应该删除
static
关键字,以便它们成为实例变量。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.更改
为
static
意味着该变量由所有实例共享。 (事实上,你可以使用this
来引用静态变量,这在 Java 中是一个奇怪的现象。)Change
to
static
means the variable is shared by all instances. (The fact you can usethis
to refer to static variables is a Java oddity.)您的 nom 和 whee 字段是静态的。这意味着它们与类相关,而不是与类的对象(实例)相关。
因此,当您为 this.nom 分配一个新值时,实际上,您为 Car.nom 分配了一个值。编译器允许通过对象引用静态变量,但这是非常糟糕的做法。您应该始终按静态字段的类来引用它们:Car.nom、Car.whee。这清楚地表明 nom 和 whee 是静态的,因此由该类的所有实例共享。在这种情况下,这些字段不应该是静态的:每个 Car 实例都有自己的名称和名称(无论它是什么)。
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.