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.
One of the most elegant things about anonymous classes is that they allow you to define a one-shot class exactly where it is needed. In addition, anonymous classes have a succinct syntax that reduces clutter in your code.
In your specific case the DefaultHandler
class 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.
this is anonymous class definition. DefaultHandler is an interface and has no implementation and you are creating one just there, while creating an instance.
since DefaultHandler
is an interface it expects an object of class which implements DefaultHandler
interface. But if there is no such class or you need a different one you can create an object that satisfies this requirement by implementing the interface on the go.
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