22

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

My question is very basic why we people use @Override annotation and what is the importance of this annotation?

In Old JDK why it not show as warning, but in latest JDK it required then Why..?

Community
  • 1
  • 1
Sumit Singh
  • 23,530
  • 8
  • 71
  • 99
  • Here is discussion on the same topic [When do you use Java's @Override annotation and why?][1] ,seems helpful. [1]: http://stackoverflow.com/questions/94361/when-do-you-use-javas-override-annotation-and-why – COD3BOY Nov 10 '11 at 07:14
  • (http://docs.oracle.com/javase/tutorial/java/annotations/predefined.html)[This link might help you] – Emmanuel Angelo.R Mar 05 '14 at 05:41

4 Answers4

34

Suppose you have:

public class Foo
{
    public void bar(String x, String y) {}
}

public class Foo2 extends Foo
{
    public void bar(String x, Object y) {}
}

You really meant Foo2.bar to override Foo.bar, but due to a mistake in the signature, it doesn't. If you use @Override you can get the compiler to detect the fault. It also indicates to any reading the code that this is overriding an existing method or implementing an interface - advising them about current behaviour and the possible impact of renaming the method.

Additionally, your compiler may give you a warning if a method overrides a method without specifying @Override, which means you can detect if someone has added a method with the same signature to a superclass without you being aware of it - you may not want to be overriding the new method, as your existing method may have different semantics. While @Override doesn't provide a way of "un-overriding" the method, it at least highlights the potential problem.

Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929
6

Just to make sure at compile time that we are really overriding the method, also adds good amount to the readability of code

@Override is there since JDK 1.5, so you might get warning in prior

jmj
  • 225,392
  • 41
  • 383
  • 426
2

Using this annotation you may be sure that you are really overriding base method, not creating new one (e.g., by accidentally using wrong arguments). If you use @Override annotation, you will get compile time error if something is not right.

Vladimir
  • 9,215
  • 6
  • 32
  • 56
  • I donot get any compile time error, please let me know , what did I miss [here](http://stackoverflow.com/questions/23191807/use-of-override-annotation-in-custom-listener-class-doesnt-work-as-expected) – paul Apr 21 '14 at 06:17
1

To verify during compile time that you are actually overriding a method. IDE's can tell you immediately when you provide that annotation.

r0ast3d
  • 2,655
  • 1
  • 12
  • 18