java 的this用法实例

class Datee
{
private int year;
private int month;
private int day;

//this的用法1:
public Datee(int year,int month,int day)
{
	this.year=year;//这里定义的变量和成员变量一样会被当成局部变量
	//如果想要两个地方定义的名称一样且想要区分前面需要加this.
	//this代表对象本身  实例化那个对象是  this就代表那个对象
	this.month=month;
	this.day=day;
}

//this的用法2:
public Datee()
{
	//调用本类已经定义的其他构造方法
	this(2020,4,2);//不能写成Datee(2020,4,2);  
	//未来不和前面的混淆 需要在前面加上this
	//如果构造方法中 this 语句要写到第一个语句
	System.out.println("构造方法被调用");
	
}

//this的用法3:返回对象本身
public Datee getThis()
{
	return this;
}

public String toString()
{
	return this.year+"-"+this.month+"-"+this.day;   //这里可以省略this  
}

//拷贝构造方法
//由已经存在的对象创建新对象
public Datee(Datee oday)  //创建一个类 类型的对象
{
	this(oday.year,oday.month,oday.day);
}

}

class TestDate
{
public static void main(String[] args)
{
/*
Datee d1=new Datee(2020,4,1);
//System.out.println(d1.toString());
Datee d3=new Datee();
//System.out.println(d3.toString());
Datee d4=d1.getThis();
System.out.println(d4.toString());
*/

	//new过的都是实例化对象(创建对象)
	Datee d1=new Datee(2020,3,2);
	Datee d5=new Datee(d1);//Datee d5=d1;//new过的都是实例化对象(创建对象)
	//这里是创建的新对象   |  没有创建新对象   
	//并且把地址存到d5里   |  一个地址指向了两个值
	//与d1的地址不一样	   |  d5与d1的地址是一样的
	
	System.out.println(d5.toString());
	



}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值