Search code examples
javaabstract-classgregorian-calendar

Instantiating a Gregorian Calendar object


In Oracle Java documentation on Gregorian calendar, it gave an example:

// create a GregorianCalendar with the Pacific Daylight time zone
// and the current date and time
Calendar calendar = new GregorianCalendar(pdt);

I understand the the GregorianCalendar is a subclass of Calendar abstract class.

What I don't understand from the example is why it did not write the code as such:

GregorianCalender calendar = GregorianCalendar(pdt);

Solution

  • It is 100% possible to do it like this:

    GregorianCalender calendar = GregorianCalendar(pdt);
    

    The reason why the examples showed this:

    Calendar calendar = new GregorianCalendar(pdt);
    

    is because this is a little bit more flexible.

    Suppose your code will work with any kind of calendars. In other words, it doesn't depend on the specific details in the Gregorian calendar. In this kind of situation, you can use Calendar as the variable's type and your code will still compile and work fine.

    By using Calendar as the variable type, you allow the variable calendar to hold any type of calendar. Say your requirement changes and you are now allowing the user to choose a calendar system they want to use. Now you just need to change the part of the = sign. There is no need to change the variable's type.