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();
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()
and newInstancce()
methods create instances of the above abstract classes?Am I missing something about using an abstract class and its new Objects?
Class DocumentBuilderFactory. Defines a factory API that enables applications to obtain a parser that produces DOM object trees from XML documents. Allows the user to retrieve specific attributes on the underlying implementation.
A ParserConfigurationException is thrown if this DocumentBuilderFactory or the DocumentBuilder s it creates cannot support the feature.
That method is an abstract factory method, which returns a subclass of DocumentBuilder
, which is a (concrete) implementation.
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());
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.
That is a static abstract factory method , which will return a subtype of DocumentBuilderFactory
not the actual instance of DocumentBuilderFactory
itself.It is not like what I presume, you understand :
DocumentBuilderFactory dbf = new DocumentBuilderFactory();
DocumentBuilderFactory#newInstance() , Obtain a new instance of a DocumentBuilderFactory. This static method creates a new factory instance. This method uses the following ordered lookup procedure to determine the DocumentBuilderFactory implementation class to load.
newInstance()
will return an instance of the implementing class(subtype) of DocumentBuilderFactory
, which is not abstract and will assign reference to that object to
DocumentBuilderFactory
reference variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With