背景
我编写了一个 java 方法来在日、月和年之间导航。这是一种方法的示例:
public MyDate nextMonth(){
if (month<12){
month++;
setDay(1);
return MyDate();
}
else
nextYear();
return MyDate();
}
MyDate 是类名。构造函数如下所示:
public MyDate(int year, int month, int day) {
setYear(year);
setMonth(month);
setDay(day);
}
该方法应该返回如下值:
MyDate d1 = new MyDate(2012, 2, 28);
System.out.println(d1); // Tuesday 28 Feb 2012
System.out.println(d1.nextDay()); // Wednesday 29 Feb 2012
System.out.println(d1.nextMonth()); // Thursday 1 Mar 2012
System.out.println(d1.nextYear()); // Tuesday 1 Jan 2013
情况
因此,我为所有三个方法编写了代码,只是我无法让它返回 MyDate 类型 - 这是其他方法和 toString 等所需的。
我的问题
如何让这些方法返回 MyDate 类型?
最佳答案
return
语句应该返回当前修改对象,而不是新的MyDate对象,因此更改返回方法以使用this
返回当前对象,如下所示
public MyDate nextMonth(){
if (month<12){
month++;
setDay(1);
return this; //return current object
}
else
nextYear();
return this; //return current object
}
关于java - 在java中返回自定义数据类型(类?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33692303/