0

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);
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
S. Botei
  • 5
  • 2
  • you can pass a time zone to GregorianCalendar too. – Sundeep Jun 17 '18 at 09:59
  • In 2018 you shouldn’t use the `Calendar` nor the `GregorianCalendar` anyway. Those classes are poorly designed and long outdated. Instead use `ZonedDateTime` from `java.time`, the modern Java date and time API: `ZonedDateTime dateTime = ZonedDateTime.now(ZoneId.of("America/Los_Angeles"));`. [Link: tutorial](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Jun 17 '18 at 11:23
  • It’s a variant of “programming to an interface”. Only there is no interface for the `GregorianCalendar` functionality, so the abstract superclass `Calendar` is used, it gives you many of the same advantages. See [this question: What does it mean to “program to an interface”?](https://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface) – Ole V.V. Jun 17 '18 at 11:29
  • A detail, you need the **new** keyword in the latter example too. – Ole V.V. Jun 17 '18 at 11:30

1 Answers1

0

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.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • Thank you for your response. I came across another code example: GregorianCalendar d = new GregorianCalendar(); int today = d.get(Calendar.DAY_OF_MONTH); int month = d.get(Calendar.MONTH); if the reference variable d was created using GregorianCalendar, how could it be utilized using Calendar class? Is it because GregorianCalendar a subclass of Calendar? – S. Botei Jun 17 '18 at 10:57
  • @S.Botei Yes. Because GregorianCalendar inherits from Calendar, your are able to put an instance of `GregorianCalendar` into a variable of type `Calendar`. – Sweeper Jun 17 '18 at 11:16