Java this关键字的使用(在构造方法中)
小编:艳芬 409阅读 2020.08.25
this还有另外一种用法,使用在构造方法第一行(只能出现在第一行,这是规定,记住就行),通过当前构造方法调用本类当中其它的构造方法,其目的是为了代码复用。调用时的语法格式是:this(实际参数列表),请看以下代码:
public class Date {
private int year;
private int month;
private int day;
//业务要求,默认创建的日期为1970年1月1日
public Date(){
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 int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
}
public class DateTest {
public static void main(String[] args) {
Date d1 = new Date();
System.out.println(d1.getYear() + "年" + d1.getMonth() + "月" + d1.getDay() + "日");
Date d2 = new Date(2008 , 8, 8);
System.out.println(d2.getYear() + "年" + d2.getMonth() + "月" + d2.getDay() + "日");
}
}
运行结果如下图所示:
运行结果
我们来看看以上程序的无参数构造方法和有参数构造方法:
无参数构造和有参数构造对比
通过上图可以看到无参数构造方法中的代码和有参数构造方法中的代码是一样的,按照以上方式编写,代码没有得到重复使用,这个时候就可以在无参数构造方法中使用“this(实际参数列表);”来调用有参数的构造方法,这样就可以让代码得到复用了,请看:
public class Date {
private int year;
private int month;
private int day;
//业务要求,默认创建的日期为1970年1月1日
public Date(){
this(1970 , 1, 1);
}
public Date(int year,int month,int day){
this.year = year;
this.month = month;
this.day = day;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
}
还是使用以上的main方法进行测试,运行结果如下:
运行结果
在this()上一行尝试添加代码,请看代码以及编译结果:
public class Date {
private int year;
private int month;
private int day;
//业务要求,默认创建的日期为1970年1月1日
public Date(){
System.out.println("...");
this(1970 , 1, 1);
}
public Date(int year,int month,int day){
this.year = year;
this.month = month;
this.day = day;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
}
编译报错信息
通过以上测试得出:this()语法只能出现在构造方法第一行,这个大家记住就行了。
相关推荐
- 21道最新Java面试题剖析(数据库+JVM+微服务+高并发) 1、Map 的底层结构?(HashMap)评注:老题目了,各位面试的人员必须熟记!回答:Map是以键值对来存储对象的,它的底层实际上是数组和链表来组成的,经典的一张图如下(别人画的);当使用put方法时,先查找出数组位置是否存在对象,通过key.hashcode对数组长度取余…
- 整理+学习《Java面试题全集(上)》 1、面向对象的特征有哪些方面? 答:面向对象的特征主要有以下几个方面:抽象:抽象是将一类对象的共同特征总结出来构造类的过程,包括数据抽象和行为抽象两方面。抽象只关注对象有哪些属性和行为,并不关注这些行为的细节是什么。继承:继承是从已有类得到继承…
- 3DMAX提示和技巧 本主题标识使用 Civil View 的一些重要提示和技巧。常规使用屏幕分辨率至少为 1280x1024 的 Civil View。低于此分辨率时,一些面板将占用过多屏幕空间。 将视口设置为线框显示以达到最佳性能。 要尽可能简化用户界面,请在单个视口中工作并关闭 3ds Max 命令面…