This定义
定义
this是每个对象中,保存自身内存地址的一个引用类型的成员变量
this就表示这个对象自己
this不能出现在静态上下文中,只能出现在成员方法中
用哪个对象调用的成员方法,那么成员方法中的这个this 就表示哪个对象
This用法
用法
1 this用在成员方法中,方便区分同名的成员变量和局部变量
同名的静态变量和局部变量用类名来区分
同名的成员变量和局部变量用this来区分
int year;
int month;
int day;
public MyDate(int year,int month) {
this.year = year;
this.month = month;
}
2 用在构造方法中第一种,同上,可以用来区分同名的局部变量和成员变量
int year;
int month;
int day;
public MyDate(int year,int month) {
this.year = year;
this.month = month;
}
3 用在构造方法中第二种.用于重载调用当前类中的其他构造方法,提高代码重用性
public MyDate() {
//this.year = 1970;
//this.month = 1;
//this.day = 1;
this(1970,1,1);
}
public MyDate(int year,int month,int day) {
//重载调用当前类中其他构造方法,只能出现在构造方法第一行
this(year,month);
this.year = year;
this.month = month;
this.day = day;
System.out.println("-------");
}
4 return this;可以返回当前对象的内存地址,做到链式调用
this用在构造方法中,可以重载调用当前类中其他构造方法,提高代码重用性
public class This_01 {
static int a = 1;
int b = 2;
public This_01 m2() {
int b = 1;
System.out.println(this.b);
return this;
}
}
语法
this(参数);