java中可以实例化接口吗?

par*_*ver 3 java oop interface

我正在阅读有关 Spring Retry 的 java 教程,在那里我读到了有关 Spring Retry 的内容RetryCallback,这是一个接口

在同一个教程中,我发现了这段代码:

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

在我看来,一个匿名对象RetryCallback正在被实例化。但后来我们只是读到它是一个接口

有人可以解释这里发生了什么吗?

虽然不是必需的,但以防万一,这里有一个教程的链接

Boh*_*ian 6

这:

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

是一个匿名类。当运行此代码时,会实例化一个MyContainingClass$1实现 的类 的对象RetryCallback

当在实例方法中实例化时,匿名类具有对实例的隐式引用MyContainingClass,可以通过语法访问该实例MyContainingClass.this

请注意,1类名中的 实际上是n匿名类相对于包含类中所有匿名类的第 n个位置。