类初始化堆栈内存

类初始化堆栈内存

public class Person { private static int age; private String name; private String sex; ..(getset省略)public static void main(String[] args){ Person personA=new Person(); Person personB=new Person(); personA.setName("King"); personB.setName("Kong"); personA.setAge(21); personB.setAge(22); } }

【类初始化堆栈内存】如上例子:
  • 第一次使用Person类(类加载的时候),系统在堆内存为Person类分配空间,同事也会为static成员变量分配空间,将age初始化为0。
  • 在栈内存中存放personA,在堆内存中存放new Person()对象,personA指向这个对象。
  • 在栈内存中存放personB,在堆内存中存放new Person()对象(跟personA指向的对象不一样,重新new一个),personB指向这个对象。
  • 让堆内存中personA对象的name指向一个"King"字符串。
  • personA.setAge(21); 此时通过Person对象修改Person的类属性(因为是静态成员变量),Person类的age属性被赋值为22

    推荐阅读