在 Java 中实现抽象方法时是否应该添加 @Override 注释?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1005898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Should I add an @Override annotation when implementing abstract methods in Java?
提问by Eyvind
When overriding a non-virtual method in Java, use of the @Overrideannotation is recommended, but what if I implement an abstract method? Should I use @Overridethen as well?
在 Java 中重写非虚方法时,@Override推荐使用注解,但是如果我实现了一个抽象方法呢?那我@Override也应该用吗?
回答by Andrzej Doyle
I tend to prefer the use of @Overridein this case, so that the method gets flagged in the subclasses if the superclass changes (either removing the method altogether, or changing its signature, etc.).
@Override在这种情况下,我倾向于使用,以便在超类发生更改(完全删除方法或更改其签名等)时在子类中标记该方法。
The only real difference is that without the annotation, if the method in the superclass/interface is changed or removed, the implementation in question simply becomes a "normal" method of that class. Thus you should add the annotation if you're implementing the method solely to fulfil the contract; and you probably shouldn't add it if the method makes sense in your class regardless of any implemented interfaces or inherited abstract methods.
唯一真正的区别是,如果没有注释,如果超类/接口中的方法被更改或删除,所讨论的实现只是成为该类的“正常”方法。因此,如果您只是为了履行合同而实施该方法,则应该添加注释;如果该方法在您的类中有意义,而不管任何实现的接口或继承的抽象方法,您可能不应该添加它。
回答by Jon Skeet
Yes - again, it tells the compiler, "I really want to be overriding a method here. If there isn'ta corresponding method to override, I've made a mistake and want to be told about it!"
是的 - 再次,它告诉编译器,“我真的想在这里覆盖一个方法。如果没有相应的方法可以覆盖,我就犯了一个错误并希望被告知!”
Personally I think it's a pity that this is just an annotation rather than part of the language (as it is in C#) but that's the benefit of hindsight, of course.
就我个人而言,我认为这只是一个注释而不是语言的一部分(就像在 C# 中一样)很遗憾,但这当然是事后诸葛亮的好处。
回答by mR_fr0g
Yes. It is recommended practise by Joshua Bloch in Effective Java.
是的。Joshua Bloch 在 Effective Java 中推荐的做法。
回答by Mark
Actually, Joshua Bloch, in the final paragraph of page 178 in Effective Java (2nd Ed.), says that it's not essential for methods of concrete classes that override abstract methods to use the Overrideannotation because the compiler would give an error anyway. However, "it is not harmful to do so".
实际上,Joshua Bloch 在Effective Java(第 2 版)第 178 页的最后一段中说,重写抽象方法的具体类的方法不必使用Override注释,因为无论如何编译器都会给出错误。但是,“这样做没有害处”。
I'd recommend choosing a strategy and sticking with it consistently.
我建议选择一种策略并始终如一地坚持下去。

