this在java中使用构造方法的分析
本教程操作环境:windows7系统、java10版,DELL G3电脑。
1.用途
this.属性 = 属性值 表示赋值给当前对象属性值
this.方法() 表示调用当前对象的方法
this() 调用构造方法,在其他构造方法中调用时需要放在第一行
this作为方法参数,将当前对象作为方法参数传递
this作为返回值,将当前对象作为返回值返回
2.注意事项
(1)this() 不能使用在普通方法中,只能写在构造方法中
(2)必须是构造方法中的第一条语句
3.实例
this用于调用构造方法
public class Constract {int i=10;
//static方法不能访问实例变量
public static void main(String []args) {
Date d=new Date();
d.show();
Date d2=new Date(2019,4,7);
d2.show();
}
}
public class Date {
private int year;
private int month;
private int day;
Date(){
this(1970,1,1);
}
Date(int year,int month,int day){
this.year=year;
this.month=month;
this.day=day;
}
public void show() {
System.out.println(this.year+"年"+this.month+"月"+this.day+"日");
}
}
以上就是this在java中使用构造方法的分析,相信经过本篇的学习,大家已经成功在代码实例中实现构造方法的调用。如果对其他this用法感兴趣,也可以在课后查找资料。
以上是 this在java中使用构造方法的分析 的全部内容, 来源链接: utcz.com/z/542744.html