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());
}
}