When using the getInstance () method of the java.text.NumberFormat abstract class, what is the actual return value class?

This question extends to one that is in abstract-class-numberformat-very-confused-about-getinstance . I feel this question is different enough to merit to be asked for myself.

The answers to this question indicated that the code operator, for example

NumberFormat en = NumberFormat.getInstance(Locale.US); 

returns an object that is a subclass of the java.text.NumberFormat class. It makes sense to me why the return type cannot just be an instance of NumberFormat , as it is an abstract class. Rather, it was pointed out that the returned object is at least an instance of NumberFormat , but actually something else.

My question is this: what exactly is the class of the returned object? In the Sun documentation, only the subclasses I see are ChoicesFormat and DecimalFormat . Is there some kind of Voodoo compiler behind the scenes here?

Thanks in advance!

+4
source share
4 answers

A specific type is not specified, as it can be any subclass of NumberFormat . It may even depend on the locale you are using. For some locales, you might want ChoiceFormat run correctly, for others, DecimalFormat enough, and for the third locale, they can even return a locale-specific implementation.

The fact that it is not defined more specifically than the abstract base class allows such a change in implementation without changing the method signature for such a change.

You can easily check which particular type is returned by one particular call by calling getClass() on the returned value.

+3
source

This is an example factory template.

API designers did not want the caller to know the specific subtype of NumberFormat. If the caller "cares" about which specific classes can be returned, evil things appear, such as an instance of the statement. When this happens, the caller is suddenly “tightly bound” to a particular subclass, and not just to the “interface” (where an interface can mean a Java interface, an abstract class, or even some other non-final class).

Most OO advocates want you to shoot for "high encapsulation, loose communication."

+2
source

Why not run ...

 System.out.println(NumberFormat.getInstance(Locale.US).getClass().getName()); 

... and to know?

0
source

Using the Beanshell console in Jedit , I get the following:

 BeanShell> import java.text.NumberFormat; BeanShell> NumberFormat en = NumberFormat.getInstance(Locale.US); BeanShell> en.getClass().getName(); java.text.DecimalFormat 

I would say that DecimalFormat returns with this call.

0
source

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


All Articles