this還有另外一種用法,使用在構(gòu)造方法第一行(只能出現(xiàn)在第一行,這是規(guī)定,記住就行),通過當(dāng)前構(gòu)造方法調(diào)用本類當(dāng)中其它的構(gòu)造方法,其目的是為了代碼復(fù)用。調(diào)用時(shí)的語法格式是:this(實(shí)際參數(shù)列表),請看以下代碼:
public class Date {
private int year;
private int month;
private int day;
//業(yè)務(wù)要求,默認(rèn)創(chuàng)建的日期為1970年1月1日
public Date(){
this.year = 1970;
this.month = 1;
this.day = 1;
}
public Date(int year,int month,int day){
this.year = year;
this.month = month;
this.day = 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;
}
}
public class DateTest {
public static void main(String[] args) {
Date d1 = new Date();
System.out.println(d1.getYear() + "年" + d1.getMonth() + "月" + d1.getDay() + "日");
Date d2 = new Date(2008 , 8, 8);
System.out.println(d2.getYear() + "年" + d2.getMonth() + "月" + d2.getDay() + "日");
}
}
運(yùn)行結(jié)果如下圖所示:
圖11-12:運(yùn)行結(jié)果
我們來看看以上程序的無參數(shù)構(gòu)造方法和有參數(shù)構(gòu)造方法:
圖11-13:無參數(shù)構(gòu)造和有參數(shù)構(gòu)造對比
通過上圖可以看到無參數(shù)構(gòu)造方法中的代碼和有參數(shù)構(gòu)造方法中的代碼是一樣的,按照以上方式編寫,代碼沒有得到重復(fù)使用,這個(gè)時(shí)候就可以在無參數(shù)構(gòu)造方法中使用“this(實(shí)際參數(shù)列表);”來調(diào)用有參數(shù)的構(gòu)造方法,這樣就可以讓代碼得到復(fù)用了,請看:
public class Date {
private int year;
private int month;
private int day;
//業(yè)務(wù)要求,默認(rèn)創(chuàng)建的日期為1970年1月1日
public Date(){
this(1970 , 1, 1);
}
public Date(int year,int month,int day){
this.year = year;
this.month = month;
this.day = 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;
}
}
還是使用以上的main方法進(jìn)行測試,運(yùn)行結(jié)果如下:
圖11-14:運(yùn)行結(jié)果
在this()上一行嘗試添加代碼,請看代碼以及編譯結(jié)果:
public class Date {
private int year;
private int month;
private int day;
//業(yè)務(wù)要求,默認(rèn)創(chuàng)建的日期為1970年1月1日
public Date(){
System.out.println("...");
this(1970 , 1, 1);
}
public Date(int year,int month,int day){
this.year = year;
this.month = month;
this.day = 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;
}
}
圖11-15:編譯報(bào)錯(cuò)信息
通過以上測試得出:this()語法只能出現(xiàn)在構(gòu)造方法第一行,這個(gè)大家記住就行了。