What is @Override for in Java?

JavaOverriding

Java Problem Overview


> 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?

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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.

Solution 3 - Java

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.

Solution 4 - Java

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser65374View Question on Stackoverflow
Solution 1 - JavaRob Di MarcoView Answer on Stackoverflow
Solution 2 - JavaJon SkeetView Answer on Stackoverflow
Solution 3 - JavaMichael MyersView Answer on Stackoverflow
Solution 4 - JavaRahel LüthyView Answer on Stackoverflow