Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 605
UKDataGeek Avatar asked Feb 02 '26 23:02

UKDataGeek


1 Answers

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.

like image 146
Thorbjørn Ravn Andersen Avatar answered Feb 04 '26 11:02

Thorbjørn Ravn Andersen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!