使用Java的@Override注释的最佳实践是什么?为什么?

用@Override注释标记每个被重写的方法似乎有点过分。是否有某些编程情况需要使用@Override,而其他情况不应该使用@Override?


当前回答

@Override注释用于帮助开发人员检查是否重写父类或接口中的正确方法。当super的方法名发生变化时,编译器会通知这种情况,这只是为了与super和子类保持一致。

顺便说一句,如果我们没有在子类中声明注释@Override,但我们重写了super的一些方法,那么这个函数可以像@Override那样工作。但是当super的方法被更改时,这个方法不能通知开发人员。因为它不知道开发人员的目的——重写super的方法还是定义一个新方法?

因此,当我们想要重写该方法以使用多态性时,最好在该方法上方添加@Override。

其他回答

我尽可能多地使用它来识别方法何时被覆盖。如果你看看Scala编程语言,它们也有一个override关键字。我发现它很有用。

当你使用Override时要小心,因为你不能在starUML之后做逆向工程;首先制作uml。

最佳实践是始终使用它(或让IDE为您填充它们)

@Override有用性是检测父类中没有向下报告的变化。 如果没有@Override,你可以改变方法签名而忘记改变它的覆盖,使用@Override,编译器将为你捕获它。

有这样的安全网总是好的。

It seems that the wisdom here is changing. Today I installed IntelliJ IDEA 9 and noticed that its "missing @Override inspection" now catches not just implemented abstract methods, but implemented interface methods as well. In my employer's code base and in my own projects, I've long had the habit to only use @Override for the former -- implemented abstract methods. However, rethinking the habit, the merit of using the annotations in both cases becomes clear. Despite being more verbose, it does protect against the fragile base class problem (not as grave as C++-related examples) where the interface method name changes, orphaning the would-be implementing method in a derived class.

当然,这种情况多半是夸张的;派生类将不再编译,现在缺少重命名接口方法的实现,今天可能会使用重命名方法重构操作来处理整个代码库。

鉴于IDEA的检查无法配置为忽略已实现的接口方法,今天我将改变我的习惯和我的团队的代码审查标准。

我每次都用。它提供了更多的信息,当我在一年后重新访问代码时,我可以快速弄清楚发生了什么,而我已经忘记了我第一次想的是什么。