-1

i started learning java recently and there's on part that confuses me and i need help in.

from what i know to instanciate a java object this is the syntax

String s1 = new String("This is a string");

however the problem is lately ive come across stuff declared like this

NumberFormat numF = NumberFormat.getNumberInstance(locale);

Can someone explain this to me

  • Nothing to explain here. Read the [documentation](https://docs.oracle.com/javase/8/docs/api/java/text/NumberFormat.html) of `getNumberInstance`, it returns a `NumberFormat` object. – Maroun Apr 20 '16 at 12:22
  • This is called a *static factory method*. Check out *Effective Java 2nd Ed* Item 1 for a detailed explanation. – Andy Turner Apr 20 '16 at 12:25

1 Answers1

1

NumberFormat is an abstract class, and so, you cannot instantiate it the "normal way".

Hence, it has provided a static method getNumberInstance so that you can get a "general-purpose number format".

In your code, you are using that same method, to get an instance of NumberFormat

Also, this:

NumberFormat numF = NumberFormat.getNumberInstance(locale);

is the same as calling this:

NumberFormat numF = NumberFormat.getInstance(locale);
dryairship
  • 6,022
  • 4
  • 28
  • 54
  • There is no "hence" about providing a static factory method - plenty of abstract classes don't. I would suggest you remove that word. – Andy Turner Apr 20 '16 at 12:26
  • @AndyTurner Yeah, they don't want to provide a general purpose instance of themselves. – dryairship Apr 20 '16 at 12:27
  • @AndyTurner is hence really a bad word choice? I think of it as a synonym for "for this reason" or "so"; not as "if this then always" – flakes Apr 20 '16 at 12:33