Java: Interface with new keyword how is that possible?

前端 未结 9 1492
抹茶落季
抹茶落季 2020-12-04 08:21

I was reading some sourcecode from Java libraries, and I am confused here;

This code is from Document.java in jaxb library, and ContentVisitor is an Interfac

相关标签:
9条回答
  • 2020-12-04 08:57

    It is called anonymous type/class which implements that interface. Take a look at tutorial - Local and Anonymous Inner Classes.

    0 讨论(0)
  • 2020-12-04 09:01

    That declaration actually creates a new anonymous class which implements the ContentVisitor interface and then its instance for that given scope and is perfectly valid.

    0 讨论(0)
  • 2020-12-04 09:02

    You actually have just provided the implementation of this interface in an anonymous way. This is quite common and of course possible. Have a look here for more information.

    0 讨论(0)
  • 2020-12-04 09:03

    In the code, you're not creating an instance of the interface. Rather, the code defines an anonymous class that implements the interface, and instantiates that class.

    The code is roughly equivalent to:

    public final class Document {
    
        private final class AnonymousContentVisitor implements ContentVisitor {
    
            public void onStartDocument() {
                throw new IllegalStateException();
            }
    
            public void onEndDocument() {
                out.endDocument();
            }
    
            public void onEndTag() {
                out.endTag();
                inscopeNamespace.popContext();
                activeNamespaces = null;
            }
        }
    
        private final ContentVisitor visitor = new AnonymousContentVisitor();
    }
    
    0 讨论(0)
  • 2020-12-04 09:08

    Since the question is still actual and Java 8 brought in lambda. I must mention it. Lambda comparing with AIC has a couple of advantages.

    • readability / introduce functional programming.
    • in some cases performance.
    • lambda and AIC have different scoupe.
    0 讨论(0)
  • 2020-12-04 09:15

    Do notice where the braces open - you are declaring an inner object (called anonymous class) that implements ContentVisitor and all required methods on the spot!

    0 讨论(0)
提交回复
热议问题