Home > Back-end >  Is it possible to instantiate an interface in java?
Is it possible to instantiate an interface in java?

Time:11-30

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

CodePudding user response:

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.

CodePudding user response:

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

  • Related