this关键字
this关键字代表是对象的引用。也就是this在指向一个对象,所指向的对象就是调用该函数的对象引用。(好绕!!!)
那么:this到底是什么?
this代表所在函数所属对象的引用。
实际工作中,存在着构造函数之间的相互调用,但是构造函数不是普通的成员函数,不能通过函数名自己接调用所以sun公司提供this关键字。
class Student {
String name;
String gender;
int age;
Student() {
}
Student(String name) {
this();
this.name = name;
}
Student(String name, String gender, int age) {
this(name);
this.gender = gender;
this.age = age;
}
void speak() {
run();
System.out.println("姓名:" + name + " 性别:" + gender + " 年龄:" + age
+ " 哈哈!!!");
}
void run() {
System.out.println("run.....");
}
}
class Demo2 {
public static void main(String[] args) {
Student p = new Student("jack", "男", 20);
Student p2 = new Student("rose", "女", 18);
p.speak();
p2.speak();
}
}
注:
1.this只能在非静态中(没有static修饰的)函数使用
2.构造函数间相互调用必须放在构造函数的第一个语句中,否则编译错误
3.可以解决构造函数中对象属性和函数形参的同名问题。