[ACCEPTED]-What is @Override for in Java?-overriding

Accepted answer
Score: 56

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

For 7 example, I have seen the following error:

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

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

Score: 24

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

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

Score: 12

Nope, you pretty much nailed it.

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

Score: 2

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

More Related questions