59

Possible Duplicate:
When do you use Java’s @Override annotation and why?

Is there any reason to annotate a method with @Override other than to have the compiler check that the superclass has that method?

user65374
  • 24,139
  • 4
  • 19
  • 7

4 Answers4

56

As you describe, @Override creates a compile-time check that a method is being overridden. This is very useful to make sure you do not have a silly signature issue when trying to override.

For example, I have seen the following error:

public class Foo {
  private String id;
  public boolean equals(Foo f) { return id.equals(f.id);}
}

This class compiles as written, but adding the @Override tag to the equals method will cause a compilation error as it does not override the equals method on Object. This is a simple error, but it can escape the eye of even a seasoned developer

Rob Di Marco
  • 43,054
  • 9
  • 66
  • 56
24

It not only makes the compiler check - although that would be enough to make it useful; it also documents the developer's intention.

For instance, if you override a method but don't use it anywhere from the type itself, someone coming to the code later may wonder why on earth it's there. The annotation explains its purpose.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
12

Nope, you pretty much nailed it.

@Override tells the compiler your intent: if you tag a method @Override, you intended to override something from the superclass (or interface, in Java 6). A good IDE will helpfully flag any method that overrides a method without @Override, so the combination of the two will help ensure that you're doing what you're trying to.

Michael Myers
  • 188,989
  • 46
  • 291
  • 292
2

nope -- except that it also improves readability (i.e. in addition to whatever indicator your IDE uses, it makes it easy to spot that a method overrides a declaration in the superclass)

Rahel Lüthy
  • 6,837
  • 3
  • 36
  • 51