【Java】第六节 对象初始化过程
程序员文章站
2024-03-05 14:26:48
...
用new创建对象并初始化对象步骤
- 通过一个实例来观察对象的初始化过程:
class Student{ String name = "虎二"; String gender = "男"; int age = 19; double score = 66.5; { System.out.println("【声明并初始化后】" + "姓名:" + this.name + ",性别:" + this.gender + ",年龄:" + this.age + ",分数:" + this.score); this.name = "张三"; this.gender = "男"; this.age = 18; this.score = 88.5; System.out.println("【初始化块执行后】" + "姓名:" + this.name + ",性别:" + this.gender + ",年龄:" + this.age + ",分数:" + this.score); } public Student(String name, String gender, int age, double score) { this.name = name; this.gender = gender; this.age = age; this.score = score; System.out.println("【构造方法执行后】" + "姓名:" + this.name + ",性别:" + this.gender + ",年龄:" + this.age + ",分数:" + this.score); } } public class Test { public static void main(String[] args) { Student stu = new Student("李四","女",20,95.5); } }
- 执行结果:
【声明并初始化后】姓名:虎二,性别:男,年龄:19,分数:66.5 【初始化块执行后】姓名:张三,性别:男,年龄:18,分数:88.5 【构造方法执行后】姓名:李四,性别:女,年龄:20,分数:95.5
- 给对象的实例变量分配内存空间,默认初始化成员变量
- 成员变量声明时的初始化
- 初始化块(也叫构造代码块或非静态代码块)初始化
- 构造方法初始化
- 创建Student类型的变量,并指向刚才创建的Student对象