本文共 1760 字,大约阅读时间需要 5 分钟。
本文翻译自:
Should a method that implements an interface method be annotated with @Override
? 是否应该使用@Override
注释实现接口方法的方法?
The says: 的说:
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? 或者是吗?
参考:
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 . 这不会编译,因为它没有正确覆盖 。
The same will go for methods that implement an interface ( 1.6 and above only ) or override a Super class's method. 对于实现接口( 仅限1.6及更高版本 )或覆盖超类的方法的方法也是如此。
I would use it at every opportunity. 我会抓住每个机会。 See 请参阅
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,我会去做。
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. 如果你不这样做,你通常会在以后的库更改中没有错误,但是一个隐藏得很好的错误。
当您在创建实现接口的类期间告诉它“生成未实现的方法”时,Eclipse本身将添加@Override
注释。
转载地址:http://jbexb.baihongyu.com/