Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I add an @Override annotation when implementing abstract methods in Java?

People also ask

Do you need @override for abstract methods?

A subclass must override all abstract methods of an abstract class. However, if the subclass is declared abstract, it's not mandatory to override abstract methods.

Is @override annotation necessary?

@Override @Override annotation informs the compiler that the element is meant to override an element declared in a superclass. Overriding methods will be discussed in Interfaces and Inheritance. While it is not required to use this annotation when overriding a method, it helps to prevent errors.

What is the best reason for applying the @override annotation to a method?

The @Override annotation indicates that the child class method is over-writing its base class method. It extracts a warning from the compiler if the annotated method doesn't actually override anything. It can improve the readability of the source code.

Is it necessary to use @override in Java?

It is not necessary, but it is highly recommended. It keeps you from shooting yourself in the foot. It helps prevent the case when you write a function that you think overrides another one but you misspelled something and you get completely unexpected behavior.


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.


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.


Yes. It is recommended practise by Joshua Bloch in Effective Java.


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.