# 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";
}
}
🛠️ Auto-refactor Available
You can auto-refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:
Need help? Check out our installation guide.