Java 8 Features with Examples
Java Annotations were introduced in 1.5. Java @Override annotation is one of the default java annotation. When we use this annotation for a method, it tells compiler that we are trying to override a superclass method.
Java @Override annotation
Let’s see how we normally override a method in java.
public class BaseClass {
public void doSomething(String str){
System.out.println("Base impl:"+str);
}
}
package com.journaldev.annotations;
Now we will create a subclass overriding BaseClass doSomething
method.
package com.journaldev.annotations;
public class ChildClass extends BaseClass{
//@Override
public void doSomething(String str){
System.out.println("Child impl:"+str);
}
}
Notice that @Override annotation is commented as of now.
Now let’s create a test class to check how overriding works in java.
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:
Base 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:
of type ChildClass must override or implement a supertype method
The method doSomething(String)
Java @Override annotation benefits
It’s clear that using java @Override annotation will make sure any superclass changes in method signature will result in a warning and you will have to do necessary changes to make sure the classes work as expected.
It’s better to resolve potential issues at compile time than runtime. So always use java @Override annotation whenever you are trying to override a superclass method.