Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should we @Override an interface's method implementation?

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

like image 522
Benno Richters Avatar asked Oct 17 '08 15:10

Benno Richters


People also ask

Should I use @override when implementing interface?

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.

Is it necessary to write @override annotation of overridden 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.

Do you have to override all interface methods?

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.


2 Answers

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.

like image 54
jjnguy Avatar answered Sep 30 '22 03:09

jjnguy


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.

like image 41
Jon Skeet Avatar answered Sep 30 '22 04:09

Jon Skeet