@Override is used to perform compile-time checks to ensure that the annotated method overrides a method from the superclass. Those checks prevent you from making mistakes like introducing a new method (e.g., you had a typo or you messed up the case of a method name) or overloading a method (e.g., you used the wrong signature) when you intended to override a method. Without the annotations, the compiler has no way to identify those errors, and when you run the program the inherited version of the method executes when you're expecting your version of the method to execute.
Consider, for example:
Code:
public class Example {
public String tostring() {
return "Example";
}
}
In this case, the author intended to override toString() from Object; however, he typed 'tostring' (lower case 's') instead of 'toString'. This is not a syntax error -- 'tostring' is a valid method name. If, however, we call 'toString()' on an instance of this class, we might get something like:
Example@123456
when we expected:
Example
If, however, we used the @Override annotation:
Code:
@Override
public String tostring() {
return "Example";
}
We'll get the compile time error:
Quote:
|
Example.java:2: method does not override or implement a method from a supertype
|
The programmer can then correct the signature, and the code will compile and execute properly.