Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do we really need @Override and so on when code Java? [duplicate]

Possible Duplicate:
When do you use Java's @Override annotation and why?

I wonder what the functionality of adding @Override in front of the code we would like to override is. I have done with and without it, and it seemed that everything was just going well (at least, for me).

like image 644
zfm Avatar asked Jan 27 '11 22:01

zfm


People also ask

Does @override actually do anything?

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.

What happens if you don't use @override Java?

If you don't use the annotation, the sub-class method will be treated as a new method in the subclass (rather than the overriding method). 2) It improves the code's readability.

When should @override be used?

The annotation @Override is used for helping to check whether the developer what to override the correct method in the parent class or interface. When the name of super's methods changing, the compiler can notify that case, which is only for keep consistency with the super and the subclass.

Is @override optional in Java?

@Override is optional in Java. All it does is validate that a superclass method with the same signature exists. It doesn't work in the other direction.


2 Answers

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.

like image 147
James Kingsbery Avatar answered Sep 26 '22 20:09

James Kingsbery


what the functionality of adding @Override

It lets the compiler double-check for you when you say (by annotating) that a specified method is supposed to override a superclass method (or implement an interface method in Java 6 or later). If the method does not, in fact, override a superclass method (or implement an interface method), the compiler will flag this as an error. This often indicates that you have a typo in the method name or made a mistake in the method signature.

Do we really need @Override

Need it? Absolutely not, but its such a cheap way to

  • conveys explicitly to human reader that this is an overriding method, and
  • catches a bug at compile time that could take at least a few brain cycles to catch at run-time once you even know to look for it

... and even cheaper when your IDE is helping you include it ...

like image 43
Bert F Avatar answered Sep 25 '22 20:09

Bert F