4

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!

4

4 回答 4

3

没有指定具体类型,因为它可以是NumberFormat. 它甚至可能取决于您使用的语言环境。某些语言环境可能需要 aChoiceFormat才能正确实现,对于其他DecimalFormat语言环境就足够了,对于第三语言环境,它们甚至可能返回特定于语言环境的实现。

它没有比抽象基类更具体地定义的事实允许在实现中进行这种更改,而无需更改方法签名以适应这种更改。

通过调用返回值,您可以轻松验证某个特定调用返回了哪种具体类型。getClass()

于 2010-05-17T16:10:12.453 回答
2

这是工厂模式的一个例子。

API 设计者不想要求调用者知道 NumberFormat 的具体子类型。如果调用者“关心”可能返回的具体类,那么像 instanceof 运算符之类的邪恶事物开始出现。当发生这样的事情时,调用者突然“紧密耦合”到具体的子类,而不仅仅是“接口”(其中接口可以表示 Java 接口、抽象类甚至其他非最终类)。

大多数 OO 拥护者希望您追求“高封装、松耦合”。

于 2010-05-17T16:12:23.070 回答
0

为什么不跑...

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

……然后找出来?

于 2010-05-17T16:03:42.077 回答
0

在Jedit中使用Beanshell控制台,我得到以下信息:

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

我会说该调用返回了 DecimalFormat。

于 2010-05-17T16:07:09.323 回答