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;
}
}
Here I am using the variables:
MyFile modelFile = new MyFile("res\\model.dae");
MyFile textureFile = new MyFile("res\\diffuse.png");
System.out.println(modelFile.toString());
System.out.println(textureFile.toString());
The output is the following: http://imgur.com/a/Nu3N6
When Defining an Entity class the class variable show be private period. Unless you want to access these variable statically, as in without having to instantiate the class or using getters and setter. If you use getters and setters as you have done above, and clearly made an instance of the class you want use ensure you don't use static access modifiers for the class variables.
The modified code is-as below. package StackOverflowProblemSets;
/** * Created by HACKER on 05/06/2017. * Two different variables getting same value */ public class MyFile {
}
In
MyFile
class, you declare these fields asstatic
fields :So you can assign to them a single value as a
static
field is shared among all instances of the class.You should rather declare these fields as instance fields to have distinct values for each
MyFile
instance :Becauseof two member variables are
static
. Each objects share the values of these two variables(values are common for every objects).Remove the
static
in both variables. Then each and every object will hold a individual values for these variables.You need to know about static and local variables.
Static variables of a class are such variables which are common to all instances of that class and are shared by all of the instances. E.g. if I have a class:
and then I have the following code in a
main
method of another class:then my output will be:
This is because the variable
staticVar
is shared by bothc1
andc2
. First when the statementc1.staticVar = 4
is executed, the value ofstaticVar
for bothc1
andc2
is 4. Then the statementc2.staticVar = 8
is executed to change the value ofstaticVar
of both classes to 8.So in your problem, you have to make your
name
andpath
variables non-static to give each of yourmyFile
instances a different value of the variables.I hope this helps.
You problem is second file path is overlap of first file path. So, check this code: