两个不同的变量得到相同的值 [英] Two different variables getting same value
问题描述
我目前正在研究一个小型Java应用程序,但我遇到了一个问题。我创建了两个不同的变量,但是在运行代码之后,第一个变量获得的值与第二个变量相同。它们应该是不同的。
I am currently working on a small Java application and I ran into a problem. I create two different variables, but after I run the code, the first variable is getting the same value as the second one. They should be different.
这是我的自定义文件类:
Here is my custom file class:
public class MyFile {
private static String path;
private static String name;
private static final String FILE_SEPARATOR = "/";
public MyFile(String path) {
System.out.println(path);
this.path = "";
this.name = "";
this.path = /*FILE_SEPARATOR*/path;
String[] dirs = path.split(FILE_SEPARATOR);
this.name = dirs[dirs.length - 1];
}
public static String getPath() {
return path;
}
public static String getName() {
return name;
}
public String toString() {
return "Path: " + path + ", Name: " + name;
}
}
这里我使用的是变量:
MyFile modelFile = new MyFile("res\\model.dae");
MyFile textureFile = new MyFile("res\\diffuse.png");
System.out.println(modelFile.toString());
System.out.println(textureFile.toString());
输出如下: http://imgur.com/a/Nu3N6
推荐答案
In MyFile
类,您将这些字段声明为 static
字段:
In MyFile
class, you declare these fields as static
fields :
private static String path;
private static String name;
因此您可以为它们分配一个值 static
字段在类的所有实例之间共享。
So you can assign to them a single value as a static
field is shared among all instances of the class.
您应该将这些字段声明为实例字段,以便为每个设置不同的值MyFile
实例:
You should rather declare these fields as instance fields to have distinct values for each MyFile
instance :
private String path;
private String name;
这篇关于两个不同的变量得到相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!