[英]returning custom data type (class?) in java
我寫了一個 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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.