Java中关键字 : this 引用
为什么要有this引用
举个代码例子
public class Date {
public int year = 1008;
public int month = 6;
public int day = 11;
//不加this
public void setDay1(int year, int month, int day){
year = year;
month = month;
day = day;
}
//加上this
public void setDay2(int year, int month, int day){
this.year = year;
this.month = month;
this.day = day;
}
public void printDate1(){
System.out.println(year + "/" + month + "/" + day);
}
public void printDate2(){
System.out.println(this.year + "/" + this.month + "/" + this.day);
}
public static void main(String[] args) {
// 构造两个日期类型的对象 d1 d2
Date d1 = new Date();
d1.setDay1(2022,5,11);
d1.printDate1();
Date d2 = new Date();
d2.setDay2(2022,5,11);
d2.printDate2();
}
}
所以我们可以得出: this关键字指向的是当前对象的引用
this.属性名称
**指的是访问类中的成员变量,用来区分成员变量和局部变量(重名问题)**
this引用的特性
- this的类型:对应类类型引用,即哪个对象调用就是哪个对象的引用类型
- this只能在"成员方法"中使用,不能在静态方法中使用
- 在"成员方法"中,this只能引用当前对象,不能再引用其他对象
this() 调用当前对象的构造方法
其中()里面可以有参数,如果有参数就是调用指定的有参构造.
注意事项:
- this.方法名称 -> 表达的意思是用来访问本类的成员方法.
- this() 不能使用在普通方法中 只能写在构造方法中
- this()必须是构造方法中第一条语句
- this() 不能形成环
public class Date {
public int year;
public int month;
public int day;
public Date() {
this(2022,05,11);
System.out.println("不带参数构造方法!");
}
public Date(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public void printDate(){
System.out.println(year + "/" + month + "/" + day);
}
public static void main(String[] args) {
// 构造两个日期类型的对象 d1 d2
Date d1 = new Date();
d1.printDate();
}
}
注意
1. this可以使用在实例方法中,不能使用在静态方法中。
2. this关键字大部分情况下可以省略,什么时候不能省略呢?
在实例方法中,或者构造方法中,为了区分局部变量和实例变量,这种情况下:this. 是不能省略的。