对象创建的过程和this的本质
构造方法是创建 java 对象的重要途径,通过 new 关键字调用构造器时,构造器也确实返回该类的对象,但这个对象并不是完全由构造器负责创建。
创建一个对象分为如下四步:
- 分配对象空间,并将对象成员变量初始化为 0 或空
- 执行属性值的显示初始化
- 执行构造方法
- 返回对象的地址给相关的变量
this 的本质就是 “创建好的对象的地址” 由于在构造方法调用前,对象已经创建。因此,在构造方法中也可以使用 this 代表 “当前对象” 。
/**
* 1.this的作用
* 每创建一个对象,都会有一个this的引用变量,指向当前对象
* 在类的内部可以使用this来访问类的成员
*
* 2.this的使用 this用来访问类的成员
* ① this.id = id; 调用成员变量 如果局部变量和成员变量同名,需要使用this来区分(this.成员变量 = 局部变量)
* ② this.show(); 调用成员方法 this可以省略
* ③ this(id,name); 调用构造方法 必须是构造方法的第一条语句
*/
public class Student {
int id;
String name;
int age;
public Student(){
}
public Student(int id,String name){
this.id = id;
this.name = name;
}
public Student(int id,String name,int age){
// this.id = id;
// this.name = name;
this(id,name);
this.age = age;
}
public void show(){
System.out.println("我的学号是:"+id+",我的名字叫做:"+name+",今年"+age+"岁了");
}
public void study(){
show();
// this.show();
System.out.println("good good study,day day up !!");
}
public static void main(String[] args) {
Student stu = new Student();
stu.id = 1;
stu.name = "慢慢";
stu.age = 22;
stu.study();
Student stu2 = new Student(2,"某某",23);
stu2.study();
}
}