this()的用法 | B站Java学习笔记

本文介绍了Java中构造方法的使用,特别是this关键字在构造方法间的调用,以实现代码复用。示例展示了如何定义一个Date类,通过无参构造方法默认设置日期为1970年1月1日,以及如何通过有参构造方法创建不同日期的对象。通过使用this(),可以减少代码冗余,提高代码可读性。
  1. this除了可以使用在实例方法中,还可以用在构造方法中
  2. 新语法:通过当前的构造方法去调用另一个本类的构造方法,可以使用以下语法格式:
    this(实际参数列表)
  3. this() 这个语法作用是什么?
    回答:代码复用
  4. 重点 死记硬背
    只能出现在构造方法的第一句
    只能出现一次,不能出现两次

需求:
– 定义一个日期类,可以表示年月日信息
– 需求中要求:
如果调用无参数构造方法,默认创建的日期为: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站视频老师所有。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值