Reputation: 217
I wrote a java method to navigate between days, months and years. This is an example of one Method:
public MyDate nextMonth(){
if (month<12){
month++;
setDay(1);
return MyDate();
}
else
nextYear();
return MyDate();
}
MyDate is the class name. The constructor looks like this:
public MyDate(int year, int month, int day) {
setYear(year);
setMonth(month);
setDay(day);
}
The Method is supposed to return values like this:
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
So, I wrote the code for all three methods except I cannot get it to return a MyDate type - which is needed for other methods and toString and so on.
How do I get these kinds of methods to return a type MyDate?
Upvotes: 2
Views: 4504
Reputation: 6414
The return
statement should return current modifying object, not the new MyDate object, so change the return method to return current object using this
, as shown below
public MyDate nextMonth(){
if (month<12){
month++;
setDay(1);
return this; //return current object
}
else
nextYear();
return this; //return current object
}
Upvotes: 2