Java面向對象的內存圖的解析

Java面向對象的內存圖的解析

1. 代碼示例

Cat.class代碼

public class Cat {

//成員變量

private String name;

private Integer age;

//成員方法

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public Integer getAge() {

return age;

}

public void setAge(Integer age) {

this.age = age;

}

//構造方法

//全參構造方法

public Cat(String name, Integer age) {

this.name = name;

this.age = age;

}

//無參構造方法

public Cat() {

}

}

測試Test代碼:

public class ClassDemo01 {

public static void main(String[] args) {

//1.使用無參構造方法創建對象

Cat cat1 = new Cat();

cat1.setName("tom");

cat1.setAge(18);

//2.使用全參構造方法創建對象

Cat cat2 = new Cat("danny",19);

}

}

2. 面向對象的堆內存、棧內存、方法區的示意圖

Java面向對象的內存圖的解析

3. 面向對象,程序執行過程分析

程序的jvm中,會從左到右,從上到下遍歷代碼。

3.1運行一個class文件時,使用類加載器先將ClassDemo01類加載到方法區,main方法壓棧(入棧);

3.2 在棧中運行main方法,當jvm看到Cat時,會自動把Cat類加載到方法區;當看到局部變量cat1時,會在棧中開闢一塊空間;當看到new Cat()時,會在堆內存中開闢空間,並將堆內存中的對應地址0x222賦值給cat1;還會拿到方法區的地址值指向方法區。

3.3 在main方法中運行到cat1.setName()這一步時,並不是cat1在調用setName()方法,而是cat1根據對象給他的地址值,去堆內存中找到相應的對象,再用對象去方法區中找到setName()方法,然後將setName()方法壓到棧中(入棧),根據地址值給堆內存中的變量賦值,調用完畢setName()方法會出棧。

3.4 main方法運行結束後會出棧。


分享到:


相關文章: