Java this关键字的使用(在构造方法中)

小编:艳芬 409阅读 2020.08.25

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() + "日");
}
}
 
运行结果如下图所示:
 

运行结果
 
我们来看看以上程序的无参数构造方法和有参数构造方法:
 

无参数构造和有参数构造对比
 
通过上图可以看到无参数构造方法中的代码和有参数构造方法中的代码是一样的,按照以上方式编写,代码没有得到重复使用,这个时候就可以在无参数构造方法中使用“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方法进行测试,运行结果如下:
 



运行结果
 
在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;
}
}
 

编译报错信息
 
通过以上测试得出:this()语法只能出现在构造方法第一行,这个大家记住就行了。

关联标签: