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

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


当前回答

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

@Override有用性是检测父类中没有向下报告的变化。 如果没有@Override,你可以改变方法签名而忘记改变它的覆盖,使用@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是可以的。

我到处都用它。 关于标记方法的工作,我让Eclipse替我做,所以不需要额外的工作。

我对持续重构非常虔诚....所以,我会利用每一件小事让它进行得更顺利。

对于我来说,@Override确保我有正确的方法签名。如果我放入注释,而方法拼写不正确,那么编译器会报错,让我知道有什么地方出错了。

每当一个方法覆盖了另一个方法,或者一个方法在接口中实现了签名。

@Override注释确保您确实重写了某些内容。如果没有注释,可能会出现拼写错误或参数类型和数字不同的情况。

它允许你(好吧,编译器)在你重写的方法名上使用了错误的拼写。