paradocslover
paradocslover

Reputation: 3294

Is it possible to instantiate an interface in java?

I was going through a java tutorial on Spring Retry and there I read about RetryCallback, which is an interface.

In the same tutorial, I found this chunk of code:

retryTemplate.execute(new RetryCallback<Void, RuntimeException>() {
    @Override
    public Void doWithRetry(RetryContext arg0) {
        myService.templateRetryService();
        ...
    }
});

The way I see it, an anonymous object of RetryCallback is being instantiated. But then we just read it's an interface.

Could someone explain what's happening here?

Although not required, but just in case here's a link to the tutorial

Upvotes: 3

Views: 142

Answers (3)

Kaan
Kaan

Reputation: 5754

The question written in the title of your post:

Is it possible to instantiate an interface in java?

No, it is not possible. From 4.12.6. Types, Classes, and Interfaces in JLS (bold emphasis added by me):

Even though a variable or expression may have a compile-time type that is an interface type, there are no instances of interfaces. A variable or expression whose type is an interface type can reference any object whose class implements (§8.1.5) that interface.

Upvotes: 0

Bohemian
Bohemian

Reputation: 425033

This:

new RetryCallback<Void, RuntimeException>() {
    @Override
    public Void doWithRetry(RetryContext arg0) {
        myService.templateRetryService();
        ...
    }
}

is an anonymous class. When this code is run, an object of class MyContainingClass$1, which implements RetryCallback, instantiated.

When instantiated within an instance method, anonymous classes have an implicit reference to the MyContainingClass instance, which is accessed via the syntax MyContainingClass.this.

Note that the 1 in the class name is actually n where the anonymous class is positioned nth relative to all anonymous classes in the containing class.

Upvotes: 6

Fikret
Fikret

Reputation: 66

its just providing a inline implementation for that interface, its not instantiating the interface. its equivalent of creating a new class a that implements RetryCallback, and passing to to execute

Upvotes: 3

Related Questions