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();

?

[316 byte] By [jellystonesa] at [2007-11-27 7:03:30]
# 1
It's a [url= http://en.wikipedia.org/wiki/Factory_method_pattern]Factory method[/url].
kevjavaa at 2007-7-12 18:54:43 > top of Java-index,Java Essentials,Java Programming...
# 2
Never heard of factory methods beforeThanks =D.
jellystonesa at 2007-7-12 18:54:43 > top of Java-index,Java Essentials,Java Programming...
# 3
I would suggest open the Factory class and see for yourself what the difference is.
kilyasa at 2007-7-12 18:54:43 > top of Java-index,Java Essentials,Java Programming...
# 4

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.

malcolmmca at 2007-7-12 18:54:43 > top of Java-index,Java Essentials,Java Programming...
# 5

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 > top of Java-index,Java Essentials,Java Programming...
# 6

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!

Hippolytea at 2007-7-12 18:54:43 > top of Java-index,Java Essentials,Java Programming...