I’ve never encountered something like this and I don’t know this type of coding!
What is this? (I’m pretty new to Java)
DefaultHandler handler = new DefaultHandler() {
boolean bfname = false;
boolean blname = false;
boolean bnname = false;
boolean bsalary = false;
public void startElement(String uri, String localName,String qName,
Attributes attributes) throws SAXException {
// code
}
public void endElement(String uri, String localName,
String qName) throws SAXException {
// code
}
public void characters(char ch[], int start, int length) throws SAXException {
// code
};
After constructor calling there is a brace (!?) and it seems that there is an overriding of some methods. Then the brace is terminated with a semicolon. I’ve never seen brace after a constructor call. Is it normal? How is it called? Thank you!
p.s: on Eclipse, if i remove the semicolon, it says LocalVariableDeclarationStatement error.
That’s an anonymous class.
Anonymous classes can be useful when you want to create a class that derives from another class or interface but you don’t need to use your new class anywhere else in your code.
In your specific case the
DefaultHandlerclass is a helper class that implements several interfaces (EntityResolver,DTDHandler,ContentHandler,ErrorHandler) by providing methods that do nothing. The idea is that you can derive from this class and override only the specific methods you need. This can be much less code than directly implementing the interfaces because then you will need to provide definitions for every method, including methods that you don’t intend to use.