简体   繁体   English

在Java中使用抽象类

[英]Using an abstract class in Java

Java Documentation says NumberFormat is an abstract class. Java文档说NumberFormat是一个抽象类。 But the following line of code is confusing me. 但是以下代码使我感到困惑。

 NumberFormat nf = NumberFormat.getInstance();

How can we use this NumberFormat.getInstance() when NumberFormat is an abstract class? NumberFormat是抽象类时,我们如何使用此NumberFormat.getInstance() Can anyone help me in understanding this please? 有人可以帮我理解这一点吗?

NumberFormat.getInstance() is a static factory method , which can return an instance of a concrete subclass of the abstract NumberFormat class: NumberFormat.getInstance()是一个静态工厂方法 ,它可以返回抽象NumberFormat类的具体子类的实例:

It's something like this: 就像这样:

abstract class Instrument {
    public static Instrument getInstance() {
        return new Guitar();
    }
}

class Guitar extends Instrument { }

So, when you call: 因此,当您致电:

Instrument.getInstance();

You would get an instance of Guitar , which is a concrete subclass. 您将获得Guitar的实例,这是一个具体的子类。

getInstance()方法返回NumberFormat的子类-语言环境的默认值。

You can call NumberFormat.getInstance() because it's a static method. 您可以调用 NumberFormat.getInstance()因为它是静态方法。 You don't need an instance of a class to call a static method on that class. 您不需要类的实例即可在该类上调用静态方法。

NumberFormat.getInstance() can declare a return type of NumberFormat because it will actually return an instance of a concrete subclass - but that's compatible with NumberFormat in the same way that this works: NumberFormat.getInstance()可以声明的返回类型NumberFormat ,因为它实际上将返回一个具体子类的实例-但那是兼容NumberFormat以同样的方式,这种工作原理:

String x = "test";
Object y = x;

If you print out NumberFormat.getInstance().getClass() you'll see which actual concrete subclass is being used - but you shouldn't depend on it returning any particular class; 如果打印出NumberFormat.getInstance().getClass()您将看到正在使用哪个实际的具体子类-但您不应依赖于它返回任何特定的类; the point is that you're just meant to use methods specified on NumberFormat itself. 关键是您只打算使用NumberFormat本身上指定的方法。

默认情况下, NumberFormat.getInstance()返回非抽象的DecimalFormat实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM