Abstract class NumberFormat - very confused about getInstance ()

I am new to Java and I have a beginner question:

NumberFormat is an abstract class, so I assume that I can not instantiate it. But there is a public static (factory?) getInstance() method that allows me to do

 NumberFormat nf = NumberFormat.getInstance(); 

I'm pretty confused. I would be glad if someone tells me:

  • If there is a public method for getting an instance of this abstract class, why don't we create a constructor?
  • This is an abstract class; how can we get this static method providing us with an instance of the class?
  • Why do you choose this design? If I assume it is possible to have an instance of an abstract class (???), I don’t understand why this class should be abstract at all.

Thanks.

+4
source share
2 answers
  • The class is abstract because it is the base class for each number format in Java (this includes, for example, DecimalFormat ). Having a constructor for a substantially unknown number format is pretty useless.
  • The getInstance() method is the so-called factory method. It returns the format of the corresponding number for the current locale. Since it is not known which subclass is required at compile time, it returns NumberFormat , however the instance itself will have a subtype, obviously (since you cannot instantiate abstract classes).
  • This project gives you flexibility by allowing you to somehow determine the appropriate instance of the subclass to return at runtime without having to do too much of this design when designing and compiling. Static methods are freed from abstractness, so the class can work both as a factory and as an abstract supertype for specific implementations. If that were not the case, you would probably have a NumberFormatFactory where factory methods would be.
+8
source

Actually, what can you get from

 public static final NumberFormat getInstance() 

is ALSO a NumberFormat , but it is a specific instance of a subclass.

You cannot create an instance of an abstract class in any way so that the method cannot return a simple NumberFormat, but something that is at least equal to NumberFormat . In this case, the method is used to get the standard formatting for your locale, which will probably be DecimalFormat or some of its variants

The DecimalFormat documentation says:

To get the NumberFormat for a specific language, including locales, call one of NumberFormat's factory, such as Unix (). In general, do not call DecimalFormat constructors directly, as NumberFormat factory methods can return subclasses other than DecimalFormat.

To conclude: you can be sure that if it is abstract, then you cannot create it, nor can Java itself .. since some parts are missing in the declaration, therefore it is incomplete.

+8
source

Source: https://habr.com/ru/post/1304018/


All Articles