理解 JVM 內存分配是 Java 開發者進階的必修課。本文通過一個 Student 類示例,逐步演示程序運行時棧、堆、方法區的動態變化。
new 創建的對象實例,由 GC 管理public class Student {
private String name;
private int age;
public void study() { System.out.println("I love study!"); }
// getter/setter 省略
}
public class StudentDemo {
public static void main(String[] args) {
Student student = new Student(); // 第5行
System.out.println(student.getName() + ":" + student.getAge()); // 第7行
student.setName("John"); // 第8行
student.setAge(23); // 第9行
System.out.println(student.getName() + ":" + student.getAge()); // 第10行
student.study(); // 第12行
Student student2 = student; // 第14行
student2.setName("Jack"); // 第15行
student2.setAge(25); // 第16行
System.out.println(student2.getName() + ":" + student2.getAge()); // 第17行
System.out.println(student.getName() + ":" + student.getAge()); // 第18行
}
}
null:0 John:23 I love study! Jack:25 Jack:25
student2 = student)傳遞的是地址,非複製對象掌握內存模型,能避免「引用修改副作用」、「內存洩漏」、「OOM」等經典問題,寫出更健壯的代碼。