I am using eclipse , when I use shortcut to generate override implementations , there is an override annotation up there , I am using JDK 6 , this is all right , but under JDK 5 this annotation will cause an error, so I want to ask , if this annotation is completely useless ? Will compiler do some kind of optimization using this annotation ?
The annotation is quite valuable in that it will make it crystal clear that the new method does or does not override a method of a parent class. For example, you might might think you're overriding, but you've misspelled the method name (or that the overridden method's signature has changed in the meantime).
It's not useless. It helps the reader to understand the code and the writer to avoid errrors.
That said, JDK 5 and JDK 6 behave differently with @Override
s, so just remove them if they cause problems. They make absolutely no functional difference.
Its purpose is for the compiler to be able to tell you when the method is not in fact overriding the super class method. For example, suppose you misspelled the name, with the anotation the compiler will warn you that the method is not overriding anything, and so you'll be able to catch your error, instead of running your program and not understanding why your method never gets called.
Compile the code against the JDK that you will deploy to.
The problem is that the annotation is valid against overriding methods from a base class and methods defined in interfaces in version 6, but only against overriding methods in version 5. Thus the @override on methods defined in an interface will cause your error in JDK 5.
As others have pointed out, the @Override
annotation is really a compiler directive that instructs javac
to scream if a method annotated with @Override
does not actually override a method in its parent class (e.g. you're actually overloading because you've decided to change the method signature or you misspell the method name).
Under JDK 5, directly implementing a method from an interface is not considered overriding that method and is considered an error if annotated with @Override
.
In part due to user feedback that this was a really confusing behaviour, JDK 6 changed this behaviour and does consider it correct to annotate a method you implement from an interface with @Override
.