@Override
annotation was introduced in Java 1.5.
@Override
annotation indicates that the element is meant to override an element declared in super class.
It is not required to use this annotation while overriding a method, but using @Override
annotation helps in preventing errors.
If you do not override a method marked with @Override
correctly, the compiler will generate compilation error.
public class Employee{ private String name; /*This method will result in compilation error as * it is incorrectly trying to override equals method. */ @Override public boolean equals(Employee employee){ return name.equals(employee.name); } }
In this example, programmer is trying to override equals()
method but instead has resulted in overloaded method. If @Override
annotation is not used, compiler will not give any error as well as no exception will not be thrown at run time.
With @Override annotation, compiler will check if this method overrides a super class or interface method correctly or not. If it does not override correctly then it will throw compilation error ‘The method equals(Employee) of type Employee must override or implement a supertype method’ in this case.
So, using @Override annotation saves time by avoiding errors related to overriding.
A programmer should always consider using this @Override
annotation when dealing with many sub classes and overriding code. This will help in saving errors and debug time.
In short @Override annotation:
- Helps is saving from hard to find errors and debug time by raising compilation errors when method is not overridden correctly.
- Helps in improving readability of the code.