While setting up the parser we do
1) SAXParserFactory factory = SAXParserFactory.newInstance();
2) SAXParsser saxparser = factory.newSAXParser();
I have doubt in both of these lines.
1) For first line why can't we create the instance using the new operator ? What is the reason for making its constructor protected? Why to use newInstance, What good does it do ?
2) For second line
the newSAXParser returns an instance of SAXParser. My question is as SAXParser is an abstract class and like all abstract classes we cant make its object then what does the API mean by saying it reurns SAXParser instance?
Thanks in advance.
1. SAXParserFactory & SAXParser are part of the standard JAXP API, not an actual SAX implementation. The actual SAX implementation, eg something like Xerces from Apache, implements the standard API. But rather than having your client code have to depend explicitly on vendors SAX classes in code, the standard SAXParserFactory class has a mechanism for looking up vendors SAXParser classes (ie. that extend the SAXParser abstract class) by using system properties to specify the implementation class names (see JAXP docs for detailed description of mechanism). newInstance() is the method that performs this mechanism. Also see FactoryMethod in the GoF book.
2. If you understood 1, maybe 2 makes more sense. SAXParser is part of the standard JAXP API, not an implementation class. Abstract class or interface, its purpose is to protect the client code from having to explicitly depend on vendor's classes.
Hope that helps (and was understandable !!)