abstract class NumberFormat - very confused about getInstance()

后端 未结 2 1411
情深已故
情深已故 2020-12-19 14:23

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 pub

2条回答
  •  难免孤独
    2020-12-19 14:33

    1. 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.
    2. 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 a NumberFormat, however, the instance itself, will be of a sub-type, obviously (since you can't create instances of abstract classes).
    3. 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.

提交回复
热议问题