第五章
- this
- 总结
this总结:
-
一个对象一个this
-
this是一个变量,是一个引用。this保存当前对象的内存地址,指向自身。所以,严格意义上,this代表的就是==“当前对象”==,this存储在堆内存当中对象的内部。
-
this只能使用在实例方法中,谁调这个实例方法,this就是谁,所以this代表的是当前对象。
-
“this.”大部分情况下是可以省略的。
-
什么时候不能省略?
当实例方法传参的参数名和实例变量的参数名一样时,必须用this.name = name
-
为什么this不能使用到静态方法中? 因为this是当前对象,而静态方法的调用是不需要对象的参与的。
-
this除了可以使用在实例方法中,也可以使用在构造方法中。
新语法:通过当前的构造方法调用去另一个本类的构造方法,可以使用以下语法格式:this();
this()必须在构造方法的第一行,否则报错
this()作用:代码复用
package day3; public class Date { private int year;//年 private int month;//月 private int day;//日 public Date() { /*this.year = 1970; this.month = 1; this.day = 1;*/ this(1970,1,1);//等价于上面三行代码,是在无参构造方法中调用了下面的有参构造方法。相当于在调用无参构造方法时,给实例变量赋初始默认值,这种语法更简洁。 } public Date(int year, int month, int day) { this.year = year; this.month = month; this.day = day; } public void detail(){ System.out.println("年:"+year+" 月:"+month+" 日:"+day); } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public int getMonth() { return month; } public void setMonth(int month) { this.month = month; } public int getDay() { return day; } public void setDay(int day) { this.day = day; } }