public class Date {
public int year;
public int month;
public int day;
public void setDay(int y, int m, int d){
year = y;
month = m;
day = d;
}
public void printDate(){
System.out.println(year + "/" + month + "/" + day);
}
public static void main(String[] args) {
// 构造三个日期类型的对象 d1 d2 d3
Date d1 = new Date();
Date d2 = new Date();
Date d3 = new Date();
// 对d1,d2,d3的日期设置
d1.setDay(2020,9,15);
d2.setDay(2020,9,16);
d3.setDay(2020,9,17);
// 打印日期中的内容
d1.printDate();
d2.printDate();
d3.printDate();
}
}
结果正常输出
但形参名不下心与成员变量名相同:
public void setDay(int year, int month, int day){
year = year;
month = month;
day = day;
}
结果却是0(根本没有赋到值),此时可以用this来引用
一、什么是this引用
this
引用指向当前对象
(
成员方法运行时调用该成员方法的对象
)
,在成员方法中所有成员变量的操作,都是通过该
引用去访问
。只不过所有的操作对用户是透明的,即用户不需要来传递,编译器自动完成。
public void setDay(int year, int month, int day){
this.year = year;
this.month = month;
this.day = day;
}
//this引用的是调用成员方法的对象,也就是这里的形参
public static void main(String[] args){
Date d=new Date(); //d的地址是:Date@529
d.setDay(2020,9,15); //d的地址是:Date@529
d.printDate();
}
public void setDay(int year,int month,int day){
this.year=year; //this指代的是d,显示的地址:Date@529
this.month=month;
this.day=day;
}
public void printDate(){
System.out.println(this.year+"/"+this.month+"/"+this.day); //这里的this也是指代的是d,显示的
} // 地址:Date@529
二、this引用的特性
1、对应类类型引用,即哪个对象调用就是哪个对象的引用类型 ;
2、只能在
"
成员方法
"
中使用 ; (还可以通过this访问当前对象的非静态的成员方法,如下图)
public class Date {
public static void main(String[] args) {
test test=new test();
test.works();
}
}
class test{
public void works(){
this.work();
System.out.println("works.this....");
}
public void work(){
System.out.println("this....");
}
}
(可以用this调用该类work方法)
3、在
"
成员方法
"
中,
this
只能引用当前对象,不能再引用其他对象;
4、
this
是
“
成员方法
”
第一个隐藏的参数,编译器会自动传递,在成员方法执行时,编译器会负责将调用成员方法 对象的引用传递给该成员方法,this
负责来接收,如下图