Use @Override Annotation

Properties

Property Value
First seen in jSparrow version 2.0.0
Minimum Java version 6
Remediation cost 5 min
Links squid: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.

Requirement & Tags

Requirements

Java 6

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