Should a method that implements an interface method be annotated with @Override
?
The javadoc of the Override
annotation says:
Indicates that a method declaration is intended to override a method declaration in a superclass. If a method is annotated with this annotation type but does not override a superclass method, compilers are required to generate an error message.
I don't think that an interface is technically a superclass. Or is it?
Question Elaboration
Using the @Override annotation prevents you from making such errors. You should be in the habit of using @Override whenever you override a superclass method, or implement an interface method.
@Override annotation is used when we override a method in sub class. Generally novice developers overlook this feature as it is not mandatory to use this annotation while overriding the method.
Yes, it is mandatory to implement all the methods in a class that implements an interface until and unless that class is declared as an abstract class.
You should use @Override whenever possible. It prevents simple mistakes from being made. Example:
class C { @Override public boolean equals(SomeClass obj){ // code ... } }
This doesn't compile because it doesn't properly override public boolean equals(Object obj)
.
The same will go for methods that implement an interface (1.6 and above only) or override a Super class's method.
I believe that javac behaviour has changed - with 1.5 it prohibited the annotation, with 1.6 it doesn't. The annotation provides an extra compile-time check, so if you're using 1.6 I'd go for it.
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