为什么会有一个抽象类“ DocumentBuilderFactory”?允许实例化新实例 [英] How come an abstract class "DocumentBuilderFactory" allowed to instantiate new instance

查看:271
本文介绍了为什么会有一个抽象类“ DocumentBuilderFactory”?允许实例化新实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我一直在使用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)); 




  1. 据我所知,您无法实例化(换句话说, ,创建一个对象)用于抽象类和接口类。我正确吗?

  2. 执行 getInstance() newInstancce()方法创建上述抽象类的实例?

  1. As far as I know, you can not instantiate (in other words, create an object) for abstract and interface classes. Am I correct?
  2. Do getInstance() and newInstancce() 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆