【新手可忽略不影响继续学习】下面例子中setYear中的return this;返回了一个指向对象的指针,this.setMonth(8).setDay(20);是合法的,如果像原来的例子一样什么都不返回,就成了void.setMonth(8).setDay(20); 马克-to-win,系统就该报错了
class MyTestDate {
int year;
int month;
MyTestDate(int year, int month, int day) {
this.year = year;
this.month = month;
}
MyTestDate setYear(int year) {
this.year = year;
return this;
}
public MyTestDate setMonth(int month) {
this.month = month;
return this;
}
public String toString() {
return "" + year + "/" + month ;
}
}
public class Test {
public static void main(String[] args) {
MyTestDate date = new MyTestDate(2009, 7, 18);
System.out.println(date);
date.setYear(2009).setMonth(8);
System.out.println(date);
MyTestDate date1 = new MyTestDate(2009, 1, 1);
System.out.println(date1);
date1.setYear(2006).setMonth(6);
System.out.println(date1);
}
}
更多请看:https://blog.csdn.net/qq_44639795/article/details/103129514