Rule Definition
Using the @Override annotation every time you override a method for two benefits. Do it so that you can take advantage of the compiler checking to make sure you actually are overriding a method when you think you are.
This way, if you make a common mistake of misspelling a method name or not correctly matching the parameters, you will be warned that you method does not actually override as you think it does.
Secondly, it makes The code easier to understand because it is more obvious when methods are overwritten.
Violation Code Sample
package com.journaldev.annotations;
public class BaseClass {
public void doSomething(String str){
System.out.println("Base impl:"+str);
}
}
package com.journaldev.annotations;
public class ChildClass extends BaseClass{
//@Override
public void doSomething(String str){
System.out.println("Child impl:"+str);
}
}
package com.journaldev.annotations;
public class OverrideTest {
public static void main(String[] args) {
BaseClass bc = new ChildClass();
bc.doSomething("override");
}
}
Output of the above program is: Child impl:override
Here “bc” is of type BaseClass but at runtime it’s object of ChildClass. So when we invoke its doSomething(String str) method, it looks for the method in ChildClass and hence the output.
Now let’s change the BaseClass doSomething method like below.
//Change argument from String to Object
public void doSomething(Object str){
System.out.println("Base impl:"+str);
}
You will notice that compiler won’t throw any warnings/errors and now if you run the test program output will be: ase impl:override
The reason is that BaseClass doSomething(Object str) method is not anymore overridden by ChildClass. Hence it’s invoking BaseClass implementation. ChildClass is overloading the doSomething() method in this case.
If you will uncomment the @Override annotation in ChildClass, you will get following compile time error message
Fixed Code Sample
package com.journaldev.annotations;
public class BaseClass {
public void doSomething(String str){
System.out.println("Base impl:"+str);
}
}
Related Technologies
Technical Criterion
Programming Practices - Structuredness
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.