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..?
@Override @Override annotation informs the compiler that the element is meant to override an element declared in a superclass. Overriding methods will be discussed in Interfaces and Inheritance. While it is not required to use this annotation when overriding a method, it helps to prevent errors.
The @Override annotation indicates that the child class method is over-writing its base class method. It extracts a warning from the compiler if the annotated method doesn't actually override anything. It can improve the readability of the source code.
The @Override annotation denotes that the child class method overrides the base class method. For two reasons, the @Override annotation is useful. If the annotated method does not actually override anything, the compiler issues a warning.
@Override means you are overriding the base class method. In java6, it also mean you are implementing a method from an interface. It protects you from typos when you think are overriding a method but you mistyped something.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With