2

Given a class MyClass where I did redefine equals() and hashCode() methods, however I forgot to mention the keyword @Override such as :

public class MyClass {
    public boolean equals(Object obj){
        //Content omitted
    }

    public int hashCode(){
        //Content omitted
    }

    //Remainder omitted
}

What would be the consequences of such mistake on the design of MyClass?

UPDATE : So if I respect the method signature of the supertype class while redefining my method in the subtype class, I still override the given method although I am not mentioning the @Override keyword, right?

ecdhe
  • 421
  • 4
  • 17
  • Nothing, really. `@Override` is just a way to tell the readers of your code that this overrides a method in the superclass. – Sweeper Nov 25 '17 at 12:00

1 Answers1

3

The @Override annotation protects you from making accidental changes. For example, you might accidentally rename the method, or change its visibility, parameter list or return type.

Without the @Override annotation, the compiler will not raise any issues on such changes, but likely your program will no longer work as intended. And it may extremely difficult to detect bugs caused by such changes. For example, two instances that are supposed to be equal, will no longer be equal, because Object.equals will be used in comparisons instead of MyClass.equals.

With the @Override annotation, the compiler will be able to tell you that something went wrong, as any of the above changes will most probably lead to method declaration that doesn't match any method in the parent classes, which is a compile-time error.

In other words, adding the @Override annotation, even when optional as in this example, is for your own protection.

janos
  • 120,954
  • 29
  • 226
  • 236