- this除了可以使用在实例方法中,还可以用在构造方法中
- 新语法:通过当前的构造方法去调用另一个本类的构造方法,可以使用以下语法格式:
this(实际参数列表) - this() 这个语法作用是什么?
回答:代码复用 - 重点 死记硬背
只能出现在构造方法的第一句
只能出现一次,不能出现两次
需求:
– 定义一个日期类,可以表示年月日信息
– 需求中要求:
如果调用无参数构造方法,默认创建的日期为:1970年1月1日
当然,除了调用无参数构造方法之外,也可以调用有参数的构造方法来创建日期对象
class Date { //以后写代码都要封装,属性私有化,对外提供setter&getter
private int year;
private int month;
private int day;
public Date() {
//this.可以省略
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 void detail() {
System.out.println(year + month + day)
}
public void setYear(int year) {
this.year = year;
}
public int getYear() {
return year;
}
public void setMonth(int month) {
this.month = month;
}
public int getMonth() {
return month;
}
public void setDay(int day) {
this.day = day;
}
public int getDay() {
return day;
}
}
public class ThisTest04 {
public static void main(String[] args) {
Date d1 = new Date();
d1.detail();
Date d2 = new Date(2008, 8, 8);
d2.detail();
}
}
思考:这两段代码重复了
public Date() {
//this.可以省略
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;
}
可以改成this(实际参数列表)的方式
public Date() {
this(1970, 1, 1);
}
public Date(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
仅供学习使用,内容版权归B站视频老师所有。
本文介绍了Java中构造方法的使用,特别是this关键字在构造方法间的调用,以实现代码复用。示例展示了如何定义一个Date类,通过无参构造方法默认设置日期为1970年1月1日,以及如何通过有参构造方法创建不同日期的对象。通过使用this(),可以减少代码冗余,提高代码可读性。
537

被折叠的 条评论
为什么被折叠?



