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?
4 Answers
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.

- 102,507
- 33
- 189
- 228
-
4Also you need Java 6 to leverage this annotation. Java 5 does not allow you to place it on interface implementations. – akarnokd Jun 17 '09 at 09:03
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.

- 1,421,763
- 867
- 9,128
- 9,194
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.

- 1,884
- 2
- 25
- 36
-
The compiler would give an error anyway? You mean if a concrete class implements a method that is not an abstract method of a superclass, the compiler would complain about it? That can't be what you mean, but I can't figure out what you do mean. – LarsH Aug 12 '15 at 01:41
-
1@LarsH He means that the compiler will give an error if the concrete class fails to implement an abstract method in the superclass, which would be the case if you misspelled the name of the abstract method that the subclass needed to implement. – Ellen Spertus Nov 11 '15 at 09:51
-
1@espertus: Thanks for the clarification. So you would not get an error or warning if, as Andrzej said, the method in the superclass/interface is changed or removed. – LarsH Nov 11 '15 at 16:49
-
@LarsH Right, you would only get the error/warning if you used the Override tag. – Ellen Spertus Nov 13 '15 at 17:15