方法可以返回抽象类类型吗?

方法可以返回抽象类类型吗?

问题描述:

我在 NumberFormat 类中查找 getCurrencyInstance()方法,我看到此方法有返回类型 NumberFormat

I am looking the method getCurrencyInstance() in NumberFormat class and I see that this method has a return type of NumberFormat.

这是什么意思?

我有点困惑,因为我知道我们可以创建一个抽象类的对象。所以这个方法返回一个对象,如果这个方法没有返回一个对象它返回什么?

I am a little confused because I know that we can create an object of an abstract class. So this method returns an object and if this method doesn't return an object what does it return?

在Java中,方法可以返回抽象类或接口类型。实际返回的是一个实现该接口的对象,或者扩展该抽象类。

In Java, a method can return an abstract class or interface type. What will actually be returned is an object that implements that interface, or extends that abstract class.

静态方法NumberFormat.getCurrencyInstance()将返回一个扩展NumberFormat的具体对象。在 javadoc 中你可以看到有两个直接已知的子类:ChoiceFormat和DecimalFormat。可能有更多的实现,实际返回的内容取决于您正在使用的JVM的实现。

The static method NumberFormat.getCurrencyInstance() will return a concrete object that extends NumberFormat. In the javadoc you can see there are two direct known subclasses: ChoiceFormat and DecimalFormat. There may be more implementations and what is actually returned depends on the implementation of the JVM that you are using.