Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two different variables getting same value

Tags:

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

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: https://i.sstatic.net/083DK.jpg

like image 660
Simagdo Avatar asked Apr 24 '26 04:04

Simagdo


2 Answers

In MyFile class, you declare these fields as static fields :

private static String path;
private static String name;

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 :

private String path;
private String name;
like image 190
davidxxx Avatar answered Apr 25 '26 17:04

davidxxx


First you want to know about static keyword:

  • Attributes and methods(member of a class) can be defined as static.
  • static members do not belongs to an individual object.
  • static members are common to all the instances(objects of the same class).
  • static members are stores in static memory(a common memory location which can by everybody).

Becauseof two member variables are static. Each objects share the values of these two variables(values are common for every objects).

private static String path;
private static String name;

Remove the static in both variables. Then each and every object will hold a individual values for these variables.

like image 30
Blasanka Avatar answered Apr 25 '26 17:04

Blasanka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!