简体   繁体   English

在单个实例(Java)中更改静态变量的值

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

I have only just begun learning Java. 我才刚刚开始学习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? 现在,您为女儿创建一个实例,并将其名字设置为Ann,等等。如果她结婚或决定更改姓氏,您将如何只更改其实例的lastName值而不更改整个类?

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: 我尝试在FamilyMember类中创建一个方法来设置一个新的lastName:

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

Even tried adding 'static' before void. 甚至尝试在void之前添加“ static”。 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. 您可以删除姓氏的静态修饰符,如果要为每个实例设置一个默认值,以后可以对其进行修改,则可以为其使用多个构造函数,也可以将setter用作姓氏。

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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