在Java中实现抽象方法时是否应该添加@Override注解?
在 Java 中重写非虚方法时,建议使用 @Override
注解,但是如果我实现抽象方法怎么办? 那么我也应该使用@Override吗?
When overriding a non-virtual method in Java, use of the @Override
annotation is recommended, but what if I implement an abstract method? Should I use @Override
then as well?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在这种情况下,我倾向于使用 @Override,这样,如果超类发生更改(完全删除该方法,或更改其签名等),该方法就会在子类中被标记。
唯一真正的区别是,如果没有注释,如果超类/接口中的方法被更改或删除,那么相关的实现就变成了该类的“正常”方法。 因此,如果您只是为了履行合同而实现该方法,则应该添加注释; 如果该方法在您的类中有意义,无论任何实现的接口或继承的抽象方法如何,您可能不应该添加它。
I tend to prefer the use of
@Override
in 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.).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.
是的 - 再次,它告诉编译器,“我真的想在这里重写一个方法。如果没有相应的方法来重写,我就犯了一个错误,并且希望被告知它!”
我个人认为遗憾的是这只是一个注释而不是语言的一部分(就像在 C# 中一样),但这当然是事后诸葛亮的好处。
Yes - again, it tells the compiler, "I really want to be overriding a method here. If there isn't a 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.
是的。 这是 Joshua Bloch 在《Effective Java》中推荐的做法。
Yes. It is recommended practise by Joshua Bloch in Effective Java.
实际上,Joshua Bloch 在《Effective Java(第 2 版)》第 178 页的最后一段中指出,对于覆盖抽象方法的具体类的方法来说,使用 Override 并不是必需的。 /code> 注释,因为编译器无论如何都会给出错误。 不过,“这样做也没有坏处”。
我建议选择一种策略并始终坚持下去。
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
Override
annotation because the compiler would give an error anyway. However, "it is not harmful to do so".I'd recommend choosing a strategy and sticking with it consistently.