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. 面向对象的堆内存、栈内存、方法区的示意图 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方法运行结束后会出栈。 |
|