• Post Reply Bookmark Topic Watch Topic
  • New Topic

What did the getInstance() do in this context?  RSS feed

 
Mark Richardson
Ranch Hand
Posts: 108
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please, consider this code:



The console output is as follows:
1,000,000

I understand that we have imported the Numberformat class, therefore we were able to create an object of this class called "formatter." However, my understanding was that in order to create an object of anything, we need to use the new keyword and it should have been written like so:

I am completely thrown off by this line in the code, and the fact that we are using a method of NumberFormat: getInstance() and setting the value of whatever this gives us to formatter?
Someone, please explain the last two lines of this code to me in step-by-step, simple English. Thank you
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
getInstance() is a static method that returns a NumberFormat object. It's an example of the factory method design pattern.

If you look at the API documentation of class java.text.NumberFormat you will see that it is an abstract class. This means you cannot directly create it using new NumberFormat() - an abstract class is an "incomplete" class that must be subclassed. There are a number of (non-abstract) subclasses of NumberFormat, for example DecimalFormat and ChoiceFormat.

You can also see in the API documentation that class NumberFormat has a number of other static methods that return NumberFormat objects for various purposes, for example: getCurrencyInstance() which will return a NumberFormat object that is useful for formatting amounts of money, and getIntegerInstance() which will return a NumberFormat object for formatting integer numbers.
 
Knute Snortum
Sheriff
Posts: 4287
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Learning to find and read documentation is a vital skill for the Java programmer.  I find that if I google java 8 NumberFormat, I can quickly find the correct documentation for NumberFormat (or any class).

Alternatively, you can bookmark https://docs.oracle.com/javase/8/docs/api/ and find NumberFormat there.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!