在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屋!