本文翻译自:Should we @Override an interface's method implementation?
Should a method that implements an interface method be annotated with @Override
? 是否应该使用@Override
注释实现接口方法的方法?
The javadoc of the Override
annotation says: Override
注释的javadoc说:
Indicates that a method declaration is intended to override a method declaration in a superclass. 指示方法声明旨在覆盖超类中的方法声明。 If a method is annotated with this annotation type but does not override a superclass method, compilers are required to generate an error message. 如果使用此批注类型注释方法但不覆盖超类方法,则编译器需要生成错误消息。
I don't think that an interface is technically a superclass. 我不认为接口在技术上是超类。 Or is it? 或者是吗?
#1楼
参考:https://stackoom.com/question/tJG/我们应该-Override接口的方法实现吗
#2楼
You should use @Override whenever possible. 你应该尽可能使用@Override。 It prevents simple mistakes from being made. 它可以防止出现简单的错误。 Example: 例:
class C {
@Override
public boolean equals(SomeClass obj){
// code ...
}
}
This doesn't compile because it doesn't properly override public boolean equals(Object obj)
. 这不会编译,因为它没有正确覆盖public boolean equals(Object obj)
。
The same will go for methods that implement an interface ( 1.6 and above only ) or override a Super class's method. 对于实现接口( 仅限1.6及更高版本 )或覆盖超类的方法的方法也是如此。
#3楼
I would use it at every opportunity. 我会抓住每个机会。 See When do you use Java's @Override annotation and why? 请参阅何时使用Java的@Override注释以及为什么?
#4楼
I believe that javac behaviour has changed - with 1.5 it prohibited the annotation, with 1.6 it doesn't. 我相信javac的行为已经改变了 - 用1.5它禁止了注释,而1.6则没有。 The annotation provides an extra compile-time check, so if you're using 1.6 I'd go for it. 注释提供额外的编译时检查,所以如果你使用1.6,我会去做。
#5楼
Overriding your own methods inherited from your own classes will typically not break on refactorings using an ide. 覆盖从您自己的类继承的自己的方法通常不会使用ide在重构上中断。 But if you override a method inherited from a library it is recommended to use it. 但是如果重写从库继承的方法,建议使用它。 If you dont, you will often get no error on a later library change, but a well hidden bug. 如果你不这样做,你通常会在以后的库更改中没有错误,但是一个隐藏得很好的错误。
#6楼
当您在创建实现接口的类期间告诉它“生成未实现的方法”时,Eclipse本身将添加@Override
注释。