views:

125

answers:

6

Would you put the annotation in implementation class methods? Does it serve any purpose? If you mistype or don't have it, it is a compile error anyway.

+3  A: 

It's rather useful. If a method annotated with @Override doesn't really overrides method in a superclass you'll get a compilation error.

For example, if you have a class Foo and you create a method:

@Override 
public boolean equals (Foo foo) { ... }

then you'll get compile-time error which will tell you that equals (Foo foo) doesn't override any method in Foo's superclass.

Modern IDEs (like IntelliJ) add this annotation automatically when you use some code-generation features of the IDE.

Roman
I think the equals(Object) vs equals(Blah) is the best example of how @Override can help prevent a major (but hard to detect) programmer error.
Thien
+6  A: 

While it's not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with @Override fails to correctly override a method in one of its superclasses, the compiler generates an error.
Its better to fail fast, catch the error soon rather than later figure out you wrote hashcode() but you meant to write hashCode(). @Override helps in finding the problem sooner rather than later.

Similar questions on SO.

Also see this.

Zaki
+1  A: 

Marking a method as @Override will produce a compilation error if the API changes so no super method is available any more. Maybe that's the reason.

mklhmnn
+1  A: 

I assume you are asking about annotating methods which are defined in an implemented interface, or as abstract in a super class. In that case, you are correct that a typo in the method signature will result in a compile error with or without @Override. However, I think the annotation is still helpful to explicitly mark a method as implementing an interface. If the interface ever changes, having @Override annotations on all the implementing methods can help pinpoint which method signatures have changed and need to be updated.

More importantly, as mklhmnn mentioned in his answer, if a method is removed from the interface, the @Override annotation in your implementing class will cause a compile error. Without the annotation, you might not be aware that a method had been removed from the interface, which could lead to subtle bugs.

Jason Day
+1  A: 

I don't use it and never had a problem. I don't know why suddenly everybody starts using it (Eclipse? which I don't use either).

Refactoring is not a problem, IDE checks that for you anyway.

@Override may help code readability though, so that it's clear to HUMANS what's going on, not compilers. Although my IDE will also mark override methods graphically, it is not very prominent, but the point remains, this is something tools can do for us automatically.

irreputable
A: 

I think it's also nice to do this as an indication to yourself that the Javadoc is elsewhere, you didn't just forget it.

EJP