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

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


当前回答

它所做的另一件事是,当读取代码时,它会更明显地改变父类的行为。这有助于调试。

此外,在Joshua Block的著作《Effective Java》(第二版)中,第36项详细介绍了注释的好处。

其他回答

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

注释确实为编译器提供了关于代码的元数据,当我们重写基类的任何方法时,注释@Override用于继承的情况。它只是告诉编译器你正在重写方法。它可以避免一些常见的错误,如没有遵循正确的方法签名或在方法名称上出错等。所以使用@Override注释是一个很好的实践。

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

我认为最好在允许的情况下编写@override。它有助于编码。然而,需要注意的是,对于ecipse Helios,无论是sdk 5还是6,都允许为实现的接口方法使用@override注释。对于Galileo,无论是5还是6,@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的检查无法配置为忽略已实现的接口方法,今天我将改变我的习惯和我的团队的代码审查标准。