Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 557
paradocslover Avatar asked Mar 11 '26 22:03

paradocslover


2 Answers

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.

like image 183
Bohemian Avatar answered Mar 13 '26 12:03

Bohemian


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

like image 36
Fikret Avatar answered Mar 13 '26 14:03

Fikret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!