Java – two different variables that get the same value

I am currently working on a small java application, but I have a problem I created two different variables, but after running the code, the first variable gets the same value as the second variable They should be different

This 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;
    }
}

I use variables here:

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 as follows: http://imgur.com/a/Nu3N6

Solution

In the myfile class, you declare these fields as static fields:

private static String path;
private static String name;

Therefore, you can assign them a single value because static fields are shared among all instances of the class

You should declare these fields as instance fields to provide different values for each myfile instance:

private String path;
private String name;
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>