简体   繁体   中英

Change value of a static variable in a single instance (Java)

I have only just begun learning Java. Say if you create the following class:

class FamilyMember {
    static String lastName = "Doe";
    String name;
    int age;
}

Now you create an instance for a daughter, and set her name to, say, Ann, etc. If she gets married or decides to change her last name, how would you go about changing only her instance's value of lastName and not the entire class?

At first I tried creating two instances:

FamilyMember john = new FamilyMember();
FamilyMember ann = new FamilyMember();
ann.lastName = "Stewart";

But that changed the entire class. I tried creating a method in the FamilyMember class that would set a new lastName:

void changeLastName(String newName) {
    lastName = newName;
}

Even tried adding 'static' before void. But all those simply kept changing the value for the entire class. I found similar questions on the forum but none of them addressing this particular issue.

But that changed the entire class.

Exactly you made your lastname a class memeber and not an instance member. Class members doen't bind with instance. Hence you seeing the weird behaviour which you don't want.

just remove the static .

private String lastName = "Doe";

You can remove the static modifier for lastname, and if you want to make a default value for every instance which can be modified later, you can use multiple constructor for it, or use setter for the lastname.

eg:

class FamilyMember {
    String lastName;
    String name;
    int age;

    public FamilyMember(final String name, final int age) {
        this.lastName = "Doe";
        this.name = name;
        this.age = age;
    }

    public FamilyMember(final String lastName, final String name, final int age) 
    {
            this.lastName = lastName;
            this.name = name;
            this.age = age;
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM