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

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

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() + "日");

}

}

运行结果如下图所示:

ec2ccce4629810f210082db1057a7293.png

图11-12:运行结果

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

5cba50cf83fb27e7bfb95dfebaf5cb79.png

图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方法进行测试,运行结果如下:

53abc60730194ca044cdfd7c46d37dff.png

图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;

}

}

495c8c1ee4bbfd483c97de8f963b1614.png

图11-15:编译报错信息

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值