为什么变量的值会对所有对象发生变化 [英] Why does value of the variable changes for all objects
问题描述
我有一个班级和年龄领域。但是当我改变一个对象的年龄时,对于所有其他对象也会改变它。
I have a class and age field in that. But when I change age of an object it gets changed for all other objects too for the class.
private static int age;
任何人都可以帮忙解决这个问题吗?
Can anybody help resolving this problem?
推荐答案
静态变量是类变量所以,从变量声明中删除 static
as:
static variables are class variables so, remove static
from variable declaration as :
private int age;
根据java docs:
as per java docs :
在声明中包含static修饰符的字段称为静态字段或类变量。它们与类相关联,而不是与任何对象相关联。该类的每个实例共享一个类变量,该变量位于内存中的一个固定位置。
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.
这篇关于为什么变量的值会对所有对象发生变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!