Java中对象的内存图
首先会把执行类的.class文件加载到方法区,把main方法临时存储
main方法存入栈里
单个对象
class Person {
int age;
String name;
}
public class Main {
public static void main(String[] args) {
Person person = new Person();
person.age = 25;
person.name = "Alice";
}
}
在堆中,为Person对象分配一块内存空间,用于存储对象的实例变量age
和name
在栈中,有一个引用变量person
,它存储了堆中对象的地址,通过这个引用可以访问堆中的对象。
多个对象
public class Main {
public static void main(String[] args) {
Person person1 = new Person();
person1.age = 25;
person1.name = "Alice";
Person person2 = new Person();
person2.age = 30;
person2.name = "Bob";
}
}
堆中有两块不同的内存区域分别用于存储person1
和person2
对象。
栈中有两个引用变量person1
和person2
,分别指向堆中的不同对象。
对象引用传递
public class Main {
public static void main(String[] args) {
Person person1 = new Person();
person1.age = 25;
person1.name = "Alice";
Person person2 = person1;
}
}
堆中只有一个Person对象。
栈中有两个引用变量person1和person2,它们都指向堆中的同一个对象。
对象作为方法参数的内存图
public class Main {
public static void changePerson(Person p) {
p.age = 35;
p.name = "Charlie";
}
public static void main(String[] args) {
Person person = new Person();
person.age = 25;
person.name = "Alice";
changePerson(person);
}
}
堆中有一个Person对象。
栈中有两个区域,一个是main方法的栈帧,其中有引用变量person;另一个是changePerson方法的栈帧,其中有参数变量p。这两个变量都指向堆中的同一个对象。
原文地址:https://blog.csdn.net/qq_45910863/article/details/142304285
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!