this還有另外一種用法,使用在構造方法第一行(只能出現在第一行,這是規定,記住就行),通過當前構造方法調用本類當中其它的構造方法,其目的是為了代碼復用。調用時的語法格式是:this(實際參數列表),請看以下代碼:
public class Date {
private int year;
private int month;
private int day;
//業務要求,默認創建的日期為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() + "日");
}
}
運行結果如下圖所示:
圖11-12:運行結果
我們來看看以上程序的無參數構造方法和有參數構造方法:
圖11-13:無參數構造和有參數構造對比
通過上圖可以看到無參數構造方法中的代碼和有參數構造方法中的代碼是一樣的,按照以上方式編寫,代碼沒有得到重復使用,這個時候就可以在無參數構造方法中使用“this(實際參數列表);”來調用有參數的構造方法,這樣就可以讓代碼得到復用了,請看:
public class Date {
private int year;
private int month;
private int day;
//業務要求,默認創建的日期為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方法進行測試,運行結果如下:
圖11-14:運行結果
在this()上一行嘗試添加代碼,請看代碼以及編譯結果:
public class Date {
private int year;
private int month;
private int day;
//業務要求,默認創建的日期為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:編譯報錯信息
通過以上測試得出:this()語法只能出現在構造方法第一行,這個大家記住就行了。