使用Java的@Override注释的最佳实践是什么?为什么?
用@Override注释标记每个被重写的方法似乎有点过分。是否有某些编程情况需要使用@Override,而其他情况不应该使用@Override?
使用Java的@Override注释的最佳实践是什么?为什么?
用@Override注释标记每个被重写的方法似乎有点过分。是否有某些编程情况需要使用@Override,而其他情况不应该使用@Override?
当前回答
如果您发现自己经常重写(非抽象)方法,您可能需要检查一下您的设计。当编译器无法捕捉错误时,它非常有用。例如,尝试在ThreadLocal中覆盖initValue(),这是我已经做过的。
在实现接口方法(1.6+特性)时使用@Override对我来说似乎有点过度。如果你有大量的方法,有些重写了,有些没有,这可能又是糟糕的设计(如果你不知道,你的编辑器可能会显示哪个是哪个)。
其他回答
最佳实践是始终使用它(或让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的检查无法配置为忽略已实现的接口方法,今天我将改变我的习惯和我的团队的代码审查标准。
对于我来说,@Override确保我有正确的方法签名。如果我放入注释,而方法拼写不正确,那么编译器会报错,让我知道有什么地方出错了。
覆盖注释用于利用编译器,用于检查是否实际上覆盖了父类中的方法。如果你犯了任何错误,比如拼写错误的方法名,没有正确匹配参数的错误,它被用来通知
使用@Override注释可以在编译时防止常见的编程错误。它会抛出一个编译错误,如果你在一个方法上有注释,而你实际上没有重写超类方法。
最常见的情况是,当您更改基类中的一个方法以拥有一个不同的参数列表时,这是有用的。子类中用于覆盖超类方法的方法将不再这样做,因为方法签名已更改。这有时会导致奇怪和意外的行为,特别是在处理复杂的继承结构时。@Override注释可以防止这种情况。