java面向对象数组的代码解析2(尚硅谷记录)

public class test1 {
	public static void main(String[] args) {
		Student[] stus = new Student[5];  //第一句解析
		stus[0] = new Student();      // 第二句解析
		// ......
	}
}

class Student{
	String name; // 第二句解析
	int age=1; // 第二句解析
	boolean sex; // 第二句解析
}

解析过程如下:

1、Student[] stus = new Student[5];  //第一句解析

类似于 int[] arr = new arr[5]; 

左边:栈空间声明了1个变量,为 stus;

右边:堆空间声明了1个数组,长度为5;而且每个数组都是 Student引用类型的,没有赋值,所以默认值为null;  首地址值假如为 0x7788

赋值运算:将堆空间的 首地址值假如为 0x7788赋值给左边栈空间的变量stus;

图例:

2、stus[0] = new Student();      // 第二句解析

class Student{
    String name; // 第二句解析
    int age=1; // 第二句解析
    boolean sex; // 第二句解析
}
 

这样写的原因:1、需要为stus[0] 赋值,因为stus是Student类型,所以需要赋值Student类型;

                         2、由于需要赋值的是Student类的对象(即stus[0]),所以需要new Student();

存储过程:

                        3、所有new的对象都在堆里存,故堆里申请4个连续的结构存储,首地址值为0x1122,number/state/score都是默认值,随后state赋值为1

注:引用类型的变量只能存null或对象的地址值,即stu[0] 只能是null,或者存 地址值x01122

图例:

猜你喜欢

转载自blog.csdn.net/weixin_46932303/article/details/114552683
今日推荐