Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Interface with new keyword how is that possible?

Tags:

java

interface

People also ask

Can we use new with interface in Java?

No, you cannot instantiate an interface. Generally, it contains abstract methods (except default and static methods introduced in Java8), which are incomplete.

How does new keyword work in Java?

The new keyword in Java instantiates a class by allocating it a memory for an associated new object. It then returns a reference for that memory. To create the objects which are the blueprints of class. This new keyword in Java allocates the memory at the runtime itself.

Is it possible for an interface to implement another?

An interface can extend any number of interfaces but one interface cannot implement another interface, because if any interface is implemented then its methods must be defined and interface never has the definition of any method.

Can we use this keyword in interface Java?

So, if and when you create an object of this "Interface" (by implementing it in another class of course), the this keyword will represent that specific object. Then, you can have, InterfaceOne one = new ClassOne(); one.


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();
}

It's valid. It's called Anonymous class. See here

We've already seen examples of the syntax for defining and instantiating an anonymous class. We can express that syntax more formally as:

new class-name ( [ argument-list ] ) { class-body }

or:

new interface-name () { class-body }

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


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.