# Use @Override Annotation
# Description
This rule adds the @Override
annotation to methods overriding or implementing parent class methods.
Even though adding @Override
is not mandatory, using this annotation is considered a best practice for
two main reasons:
- It ensures that the method signature is a sub-signature of the overridden method.
- It improves the readability.
# Benefits
Improves the readability by making it clear that the methods are overridden and helps avoiding potential bugs arising from unintended changes in method signatures.
# Tags
# Code Changes
# Overriding method from parent class
Pre
class Parent {
public void foo() {
print("Parent");
}
}
class Child extends Parent {
public void foo() {
print("Child");
}
}
Post
class Parent {
public void foo() {
print("Parent");
}
}
class Child extends Parent {
@Override
public void foo() {
print("Child");
}
}
# Overriding method from implemented interface
Pre
interface IFoo {
String findFoo();
}
class Foo {
public String findFoo() {
return "Foo";
}
}
Post
interface IFoo {
String findFoo();
}
class Foo {
@Override
public String findFoo() {
return "Foo";
}
}
Use a Java Refactoring Tool
Automate this Refactoring system-wide
You can apply this refactoring for free with the jSparrow Eclipse IDE plug-in.
Install the plug-in for Eclipse IDE: Eclipse Marketplace.