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

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


当前回答

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

其他回答

这里有很多好的答案,所以让我提供另一种看待它的方式……

编码时没有多余的东西。输入@override不需要花费任何成本,但是如果您拼写错了方法名或签名稍有错误,节省的成本可能是巨大的。

可以这样想:在你浏览这里并输入这篇文章的时间里,你所花费的时间比你余生输入@override的时间还要多;但是它防止的一个错误可以节省你的时间。

Java尽其所能确保您在编辑/编译时不会犯任何错误,这是一种几乎免费的方法来解决整个类型的错误,这些错误在全面测试之外的任何其他方法都无法预防。

你能在Java中提出一种更好的机制来确保当用户想要重写一个方法时,他实际上做到了吗?

另一个巧妙的效果是,如果您不提供注释,它将在编译时警告您不小心覆盖了父方法——如果您不打算这样做,这可能会很重要。

最好将它用于打算重写的每个方法,以及Java 6+,用于打算作为接口实现的每个方法。

首先,它会在编译时捕获像“hashcode()”而不是“hashcode()”这样的拼写错误。当真正的原因是您的代码从未被调用时,调试为什么您的方法的结果似乎与您的代码不匹配可能会令人困惑。

同样,如果一个超类改变了一个方法签名,旧签名的重写就会被“孤立”,留下令人困惑的死代码。@Override注释将帮助您识别这些孤儿,以便对它们进行修改以匹配新签名。

接口实现上的@Override是不一致的,因为在java中没有“覆盖接口”这样的事情。

@Override on interface implementation is useless since in practise it catches no bugs that the compilation wouldn't catch anyway. There is only one, far fetched scenario where override on implementers actually does something: If you implement an interface, and the interface REMOVES methods, you will be notified on compile time that you should remove the unused implementations. Notice that if the new version of the interface has NEW or CHANGED methods you'll obviously get a compile error anyways as you're not implementing the new stuff.

在1.6中不应该允许接口实现@Override,而不幸的是,eclipse选择自动插入注释作为默认行为,我们得到了大量杂乱的源文件。在阅读1.6代码时,您无法从@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的检查无法配置为忽略已实现的接口方法,今天我将改变我的习惯和我的团队的代码审查标准。

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