Search code examples
javatimeapi-designperiod

Why does java.time.Period have no constructor?


Instead, Period.of(int, int, int) must be used, or another static method in the same vein.

What's the reasoning behind this?


Solution

  • The main reason - it is util class and most of util classes should be used in static manner (at least java architects wish so). You can compare it with using java.lang.Math.

    The second reason, I suggest - it is reflection and serialization. I think dealing with Period.class is more convinient, but it's only suggestion. Inside implementation they have static method create() and always use create() instead of constructor.

    You can also look at source code. For example, here: http://hg.openjdk.java.net/jdk9/jdk9/jdk/file/e63cf6b55a95/src/java.base/share/classes/java/time/Period.java

    public static final Period ZERO = new Period(0, 0, 0);
    
    public static Period of(int years, int months, int days) {
        return create(years, months, days);
    }
    private static Period create(int years, int months, int days) {
        if ((years | months | days) == 0) {
            return ZERO;
        }
        return new Period(years, months, days);
    }
    private Period(int years, int months, int days) {
        this.years = years;
        this.months = months;
        this.days = days;
    }