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