Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is @Override for in Java? [duplicate]

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?

like image 435
user65374 Avatar asked Feb 18 '09 14:02

user65374


People also ask

What does @override in Java do?

The @Override annotation is one of a default Java annotation and it can be introduced in Java 1.5 Version. 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.

Is it necessary to use @override in Java?

It is not necessary, but it is highly recommended. It keeps you from shooting yourself in the foot. It helps prevent the case when you write a function that you think overrides another one but you misspelled something and you get completely unexpected behavior.

Why do we override clone method?

Because, for a class to be cloned, you need to implement the Cloneable interface. And then your class uses the clone method of Object class instead. Because, Cloneable interface doesn't exactly have any method for cloning . It would be a better option to use Copy Constructor instead.

Is it necessary to override clone method in Java?

Therefore, while overriding the clone() method it is recommended to declare it public instead of protected so that it is access-able from a class in any location in the system. While overriding methods the method in the child class must not have higher access restrictions than the one in the superclass.


2 Answers

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

like image 172
Rob Di Marco Avatar answered Oct 01 '22 12:10

Rob Di Marco


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.

like image 33
Jon Skeet Avatar answered Oct 01 '22 10:10

Jon Skeet