Search code examples
javainstantiation

When do I use New to instantiate a class


I am just going through a tutorial and the instructor seemed to gloss over something which didn't make sense

In Java if I am looking to instantiate a new Gregorgian Date Object I would use:

GregorianCalendar gc= new GregorianCalendar (2010,1,14);

but if I am looking to use the Data Format object I would use:

DateFormat df = DateFormat.getDateInstance();
  1. I would really like to understand why dateformat doesn't follow the first way of instantiating the class?

  2. How would I know to lookout in future for a similar gotcha?


Solution

  • You should always consult the API documentation to see how you are to use it.

    A new X() always create a new object so if you have multiple places you need it, you end up with multiple X'es which may be inefficient if a single X would do.

    The .getDateInstance() call is a Factory that allow the API to decide by itself whether to return the same X even to multiple callers or a new one to each. For very expensive but reusable/sharable objects this is the typical way you get them.

    The Calendar API was donated to Java a very long time ago and is not as well designed as could be. These days the typical response to "I have problem X with Calendar and/or java.util.Date" in java is to use the Joda library which is well designed. For new code using Java 8 or later, use the new java.time classes as commented by Basil Bourque.