Question about creating new objects
When creating a DocumentBuilderFactory Object, why is the code written like this:
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
as opposed to
DocumentBuilderFactory docBuilderFactory =new DocumentBuilderFactory();
?
Factory classes like this are typically abstract classes which do little more than define an interface and the getInstance() methods. The class that getInstance() will actually instanciate will be a concrete implementation from a particular implementation of the DOM parser. This pattern allows whatever implementation happens to have been supplied to be automatically be used without your code having to concern itself.
The concrete factory will then create concrete implementations of the various interfaces like DOMPaser, using the implementations in the actual library.
1) Is there even a public constructor that will allow you to do the second one?
2) WIth the second one, you're getting exactly a new DocumentBuilderFactory. With the first one (the factory method), you could be getting an instance of DBF or any subclass of DBF. In addition, it may not be creating a new instance, but just returning a reference to an existing instance.
jverda at 2007-7-12 18:54:43 >

I assume we're talking about javax.xml.parsers.DocumentBuilderFactory.
Note that you can't write the following:
DocumentBuilderFactory docBuilderFactory = new DocumentBuilderFactory();
because, among other reasons, DocumentBuilderFactory is abstract!