我有一个类(class)和年龄字段。但是,当我更改对象的年龄时,该类的所有其他对象也会更改。
private static int age;
谁能帮忙解决这个问题吗?
最佳答案
静态变量是类变量,因此,从变量声明中删除static
:
private int age;
根据 java 文档:
Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory.
关于java - 为什么所有对象的变量值都会改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19957561/