Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What type of Java constructor call is this?

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.

like image 326
Angelo Avatar asked Feb 06 '12 22:02

Angelo


2 Answers

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.

like image 161
Mark Byers Avatar answered Nov 01 '22 17:11

Mark Byers


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.

like image 42
destan Avatar answered Nov 01 '22 17:11

destan