Aurora Rossi Aurora Rossi - 3 months ago 21
Java Question

Changing a static variable with a static method

I'm trying to change a private static variable with via a static method and BlueJ says that I can't because the variable I'm trying to change (which is declared as static) is non-static:

public class Playerinfo {
private static String name = ""; //Stores the name of the 'player'
public static void setname(String name) {
this.name = name;
}
}


The variable is called name and the method is called setname. I know that I can do this:

Playerinfo.name = (insert variable here)


I don't like the above because I wish to have the name variable in Playerinfo declared as private as not to be meddled with by other classes that easily.

Answer

There is no this inside a static method.

Your best bet is to rename the parameter of the method:

public class Playerinfo {
    private static String name = ""; //Stores the name of the 'player'
    public static void setname(String newName) {
        name = newName;
    }
}