抽象类 NumberFormat - 对 getInstance() 非常困惑
我是 Java 新手,有一个初学者问题:
NumberFormat
是一个抽象类,因此我认为我无法创建它的实例。但是有一个公共静态(工厂?)方法 getInstance()
允许我做
NumberFormat nf = NumberFormat.getInstance();
我很困惑的事情。如果有人能给我提示,我会很高兴:
- 如果有一个公共方法来获取这个抽象类的实例,为什么我们没有一个构造函数呢?
- 这是一个抽象类;我们怎样才能让这个静态方法给我们一个类的实例呢?
- 为什么选择这样的设计?如果我假设可能有一个抽象类的实例(???),我根本不明白为什么这个类应该是抽象的。
谢谢。
I'm new to Java and I have a beginner question:
NumberFormat
is an abstract class and so I assume I can't make an instance of it. But there is a public static (factory?) method getInstance()
that allow me to do
NumberFormat nf = NumberFormat.getInstance();
I'm quite confuse. I'll be glad if someone could give me hints on:
- If there is a public method to get an instance of this abstract class, why don't we have also a constructor?
- This is an abstract class ; how can we have this static method giving us an instance of the class?
- Why choosing such a design? If I assume it's possible to have an instance of an abstract class (???), I don't get why this class should be abstract at all.
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
DecimalFormat
)。对于本质上未知的数字格式有一个构造函数是毫无用处的。getInstance()
方法是所谓的工厂方法。它返回当前区域设置的匹配数字格式。由于在编译时不知道需要哪种子类,因此它返回一个NumberFormat
,但是,实例 本身将属于子类型,显然(因为您无法创建抽象类的实例)。NumberFormatFactory
。DecimalFormat
, for example). Having a constructor for an essentially unknown number format is pretty useless.getInstance()
method is a so-called factory method. It returns a matching number format for the current locale. Since it is not known what kind of sub-class is required at compile-time, it returns aNumberFormat
, however, the instance itself, will be of a sub-type, obviously (since you can't create instances of abstract classes).NumberFormatFactory
somewhere which would have the factory methods.实际上,您可以从中获取
ALSO一个
NumberFormat
,但它是它的子类的具体实例。无论如何,您都无法实例化抽象类,因此该方法不能返回普通的 NumberFormat,而只能返回 至少
NumberFormat
的内容。在这种情况下,该方法用于获取您的语言环境的默认格式化程序,该格式化程序可能是DecimalFormat
或其某些变体。在
DecimalFormat
的文档中,它指出:最后:你可以确定,如果它是抽象的,那么你无法实例化它,Java 本身也不能......因为声明缺少一些部分,所以它是一个真正的不完整类型。
Actually what you can obtain from
is something that is ALSO a
NumberFormat
, but it is a concrete instance of a subclass of it.You can't in anyway instantiate an abstract class so that method can't return a plain NumberFormat but something that is at least a
NumberFormat
. In this case the method is used to obtain a default formatter for your locale that will probably be aDecimalFormat
or some variations of itIn the documentation of
DecimalFormat
it states:To end: you can be sure, if it's abstract, then you cannot instantiate it, neither Java itself can.. since the declaration is missing some parts so it's a real incomplete type.