@override mandatory in Java?

21

If I have an abstract class Pessoa with an abstract method lerNome when I'm implementing this method in my João class should I make use of @Override in lerNome ? The same thing happens when I use interfaces?

    
asked by anonymous 18.09.2014 / 17:36

3 answers

20

Yes, you should do this for the compiler to do the check and prevent it from overwriting the wrong method (perhaps with the wrong signature), "configuration "the correct method and possibly calling the method in the wrong class. With it you avoid the misunderstanding by a typo, for example. With it you will get a warning indicating the problem.

warning There is no obligation to solve the problem in fact for the program to compile, but as always one should consider warnings as if they were mistakes, let's say it's "morally" mandatory. Either way it is easier to keep a code with explicit information than your intention is to override the method.

This is true for methods declared in interfaces as well.

More information about why this annotation exists and how it works can be obtained in this answer .

    
18.09.2014 / 17:44
2

In classes that implement methods of an interface as in subclasses that subscribe to methods in superclasses, this annotation is not mandatory , but it informs the compiler that the "annotated" method subscribes to a method your superclass (including interfaces).

Reference (very objective):

link

    
18.09.2014 / 18:23
1

It is recommended, not mandatory , because if you work with JREs legacy as 1.4 or previous, there are no annotations, so in this case YOU SHOULD NOT > use @override, it's just a convention to make it easier to identify overwritten methods, that's all.

    
23.05.2015 / 02:07