What type of Java constructor call is this?

I've never encountered such a thing. I don't know this type of coding!

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 qName) throws SAXException {

                // code

            }

            public void characters(char ch[],int start,int length) throws SAXException {

                // code
        };

There is a brace (!?) after the constructor call, There seems to be some rewriting of methods Then terminate the bracket with a semicolon I've never seen braces since the constructor call Is this normal? What is your name? thank you!

p. S: on eclipse, if I delete the semicolon, it means that the local variable declaration statement is wrong

Solution

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 the new class anywhere else in your code

In your specific case, defaulthandler class is an auxiliary class, which implements multiple interfaces (entityresolver, dtdhandler, contenthandler, errorhandler) by providing methods that do not perform any operation The idea is that you can derive from this class and override only the specific methods you need This is much less code than implementing the interface directly, because you need to provide definitions for each method, including methods you don't intend to use

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>