This question expands upon the one at abstract-class-numberformat-very-confused-about-getinstance. I feel that this question is different enough to merit being asked on its own.
In the answers to that question, it was stated that a code statement such as
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 can’t be just an instance of NumberFormat since that is an abstract class. Rather, it was stated that the returned object is at least an instance of NumberFormat, but actually something else.
My question is this: what specifically is the class of the object that is returned? In the Sun documentation the only subclasses I see are ChoicesFormat and DecimalFormat. Is there some sort of behind the scenes compiler voodoo going on here?
Thanks in advance!
The specific type is not specified, because it can be any subclass of
NumberFormat. It might even depend on the locale you use. Some locales may require aChoiceFormatto implement correctly, for othersDecimalFormatis sufficient and for a third locale they might even return a locale-specific implementation.The fact that it’s not defined more specifically than the abstract base class allows this kind of change in the implementation without having to change the method signature to accommodate such a change.
You can easily verify which concrete type is returned by one specific call by calling
getClass()on the returned value.