[英]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.