抽象类“DocumentBuilderFactory"怎么来的?允许实例化新实例 [英] How come an abstract class "DocumentBuilderFactory" allowed to instantiate new instance
问题描述
最近,我一直在使用 XML 解析器.这对我来说才刚刚开始,我设法了解如何在 Java 中使用 DOM 解析器类,即 DocumentBuilderFactory
和 DocumentBuilder
来解析 XML 文档.
Recently, I have been working with XML parsers. This is just beginning for me and I managed to understand how to use DOM parser classes in java i.e. DocumentBuilderFactory
and DocumentBuilder
to parse an XML document.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
我问自己是如何允许抽象类(例如 DocumentBuilderFactory
和 DocumentBuilder
)实例化新实例的?然后在另一个例子中我看到:
What I am asking myself is how come an abstract classes, such as DocumentBuilderFactory
and DocumentBuilder
, are allowed to instantiate new instances? And then in another example I see:
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.get(Calendar.DATE));
- 据我所知,您不能为抽象类和接口类实例化(换句话说,创建一个对象).我说得对吗?
getInstance()
和newInstancce()
方法是否会创建上述抽象类的实例?
- As far as I know, you can not instantiate (in other words, create an object) for abstract and interface classes. Am I correct?
- Do
getInstance()
andnewInstancce()
methods create instances of the above abstract classes?
我是否遗漏了有关使用抽象类及其新对象的内容?
Am I missing something about using an abstract class and its new Objects?
推荐答案
那个方法是一个 抽象工厂方法,它返回一个DocumentBuilder
的子类,这是一个(具体的)实现.
That method is an abstract factory method, which returns a subclass of DocumentBuilder
, which is a (concrete) implementation.
知道对象的确切类并不重要,您只需要知道它是一个DocumentBuilder
.该方法可以返回一个在运行时决定的实例,或者它认为合适的预定实例.
The exact class of the object is not important to know, you only need to know that it's a DocumentBuilder
. The method may return an instance decided at runtime, or predetermined as it sees fit.
如果你想知道,你可以像这样打印出实际的类:
If you are curious to know, you can print out the actual class like this:
System.out.println(dbf.getClass());
<小时>
注意newInstance()
方法不要与Class
的同名方法混淆,即两者是不同的:
Note that the method newInstance()
is not to be confused with the method of the same name of Class
, ie these two are different:
// a static method of this class
DocumentBuilderFactory.newInstance();
// an instance method of Class
DocumentBuilderFactory.class.newInstance();
一个不幸的名字选择肯定会引起混淆.
An unfortunate choice of name sure to have caused confusion.
这篇关于抽象类“DocumentBuilderFactory"怎么来的?允许实例化新实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!