抽象类NumberFormat - 对getInstance()非常困惑 [英] abstract class NumberFormat - very confused about getInstance()
本文介绍了抽象类NumberFormat - 对getInstance()非常困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Java的新手,我有一个初学者的问题:
I'm new to Java and I have a beginner question:
NumberFormat
是一个抽象类,所以我假设我无法做出它的实例。但是有一个公共静态(工厂?)方法 getInstance()
允许我这样做
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:
- 如果有一个公共方法来获取这个抽象类的实例,为什么我们还没有构造函数?
- 这是一个抽象类;我们怎么能有这个静态方法给我们一个类的实例?
- 为什么选择这样的设计?如果我假设它有可能有一个抽象类的实例(???),我不明白为什么这个类应该是抽象的。
谢谢。
推荐答案
- 该类是抽象的,因为它是Java中每种数字格式的基类(例如,这包括
DecimalFormat
)。具有构造为基本上未知数格式是相当无用。 - 的
的getInstance()
方法是一种所谓的工厂方法。它返回当前语言环境的匹配数字格式。由于不知道在编译时需要什么类的子类,它返回NumberFormat
,但是,实例本身,将显然是一个子类型(因为你不能创建抽象类的实例)。 - 这种设计为你提供了以某种方式确定正确的灵活性子类实例在运行时返回,而不会在设计/编译时使设计过多。静态方法不受抽象,因此类可以作为工厂和用于具体实现的抽象超类型。如果不是这种情况,你可能会有一个
NumberFormatFactory
某处有工厂方法。
- The class is abstract because it is the base class for every number format in Java (this includes
DecimalFormat
, for example). Having a constructor for an essentially unknown number format is pretty useless. - The
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). - This design gives you the flexibility of somehow determining the proper subclass instance to return at runtime without making too much of that design rigid at design/compile time. Static methods are exempt from being abstract so a class can work as both a factory and an abstract supertype for concrete implementations. If this weren't the case you'd probably have a
NumberFormatFactory
somewhere which would have the factory methods.
这篇关于抽象类NumberFormat - 对getInstance()非常困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文