java 抽象类的createinstance,抽象类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.

解决方案

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 a NumberFormat, 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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值