Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of the @Override annotation? [duplicate]

Tags:

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

like image 605
Sumit Singh Avatar asked Nov 10 '11 07:11

Sumit Singh


People also ask

What is the @override annotation used for?

@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.

What is the purpose of @override in Java?

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.

What does @override mean in spring?

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.

What does @override mean Code?

@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.


2 Answers

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.

like image 189
Jon Skeet Avatar answered Dec 31 '22 01:12

Jon Skeet


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

like image 41
jmj Avatar answered Dec 31 '22 02:12

jmj