在 Java 中实现抽象方法时是否应该添加 @Override 注释? [英] Should I add an @Override annotation when implementing abstract methods in Java?
问题描述
在 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?
推荐答案
在这种情况下,我倾向于使用 @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.
这篇关于在 Java 中实现抽象方法时是否应该添加 @Override 注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!