您的位置 首页 java

java中请给出一个return this的例子

【新手可忽略不影响继续学习】下面例子中setYear中的return this;返回了一个指向对象的指针,this.setMonth(8).setDay(20);是合法的,如果像原来的例子一样什么都不返回,就成了 void .setMonth(8).setDay(20); 马克-to-win,系统就该报错了
马克- to-win:马克 java社区:防盗版实名手机尾号: 73203。

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

}
}

篇幅有限更多请见扩展链接:

文章来源:智云一二三科技

文章标题:java中请给出一个return this的例子

文章地址:https://www.zhihuclub.com/187328.shtml

关于作者: 智云科技

热门文章

网站地图