In java.time.Period class, what are the purposes of withDays(), withMonths(), withYears()

Viewed 894

I noticed that the java.time.Period class contains a few instance methods that behave the same as the available static factory methods.

  • .withDays() behaves the same as Period.ofDays()
  • .withMonths() behaves the same as Period.ofMonths()
  • .withYears() behaves the same as Period.ofYears()

These instance methods are confusing in that they create a new Period and return them, but without taking into consideration the state of the Period they are called on.

Period p = Period.ofWeeks(3);
p = p.withDays(2);

It seems logical that this would return a period of 3 weeks, 2 days, but it returns only a period of 2 days. This is the same as if I'd called Period.ofDays(2).

Also, there are five other static factory methods without analogous instance methods.

So, is there a reason that these three instance methods would exist? If so, what's the use case?

2 Answers
Related