# Use @Override Annotation

# Properties

Property Value
Rule ID OverrideAnnotation
First seen in jSparrow version 2.0.0
Minimum Java version 6
Remediation cost 5 min
Links S1161

# 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:

  1. It ensures that the method signature is a sub-signature of the overridden method.
  2. 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.

# 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";
    }
}

Automatic Application of This Rule

The automatic application of this rule is supported in the following jSparrow versions:

# Tags

1
default
You & jSparrow
default

Hey there! May I help you? 😊