gpt4 book ai didi

java - 在构造函数后面有一个覆盖方法的部分的 Java 语法是什么?

转载 作者:行者123 更新时间:2023-12-02 02:51:03 24 4
gpt4 key购买 nike

我找到了这个example使用以下代码:

CompletableFuture<T> completable = new CompletableFuture<T>() {  
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
// propagate cancel to the listenable future
boolean result = listenableFuture.cancel(mayInterruptIfRunning);
super.cancel(mayInterruptIfRunning);
return result;
}
};

这个语法是什么意思?该方法是否重写了类中的方法而不扩展它?

最佳答案

这段代码创建了一个 anonymous subclass CompletableFuture。这个匿名子类覆盖 cancel(bool)方法与新的实现。匿名子类相当于创建一个扩展 CompleteableFuture 的新类,但需要注意的是,在其他地方重用这个新子类并不简单。

@Override 在这种情况下并不是绝对必要的,但它为您提供了一些好处,如 this question 的答案所述。 :

Use it every time you override a method for two benefits. Do it so that you can take advantage of the compiler checking to make sure you actually are overriding a method when you think you are. This way, if you make a common mistake of misspelling a method name or not correctly matching the parameters, you will be warned that you method does not actually override as you think it does. Secondly, it makes your code easier to understand because it is more obvious when methods are overwritten.

Additionally, in Java 1.6 you can use it to mark when a method implements an interface for the same benefits. I think it would be better to have a separate annotation (like @Implements), but it's better than nothing.

关于java - 在构造函数后面有一个覆盖方法的部分的 Java 语法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43842611/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com