tags:

views:

2246

answers:

4

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

+8  A: 

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
+2  A: 

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)

netzwerg
+17  A: 

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
+5  A: 

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