views:

46939

answers:

24

What are the best practices for using Java's @Override annotation and why?

It seems like it would be overkill to mark every single overridden method with the @Override annotation. Are there certain programming situations that call for using the @Override and others that should never use the @Override?

+1  A: 

I use it every time. It's more information that I can use to quickly figure out what is going on when I revisit the code in a year and I've forgotten what I was thinking the first time.

Hank Gay
A: 

When you overwrite a method from a parent class you should use the @Override.

Burkhard
you forgot the 'why'...
Stu Thompson
+3  A: 

I always use the tag. It is a simple compile-time flag to catch little mistakes that I might make.

It will catch things like tostring() instead of toString()

The little things help in large projects.

jjnguy
+2  A: 

Whenever a method overrides another method, or a method implements a signature in an interface.

The @Override annotation assures you that you did in fact override something. Without the annotation you risk a misspelling or a difference in parameter types and number.

Greg Mattes
You can only use it to mark interface implementation in Java 1.6
Dave L.
A: 

It does allow you (well, the compiler) to catch when you've used the wrong spelling on a method name you are overriding.

JeeBee
+121  A: 

Use it every time you override a method for two benefits. Do it so that you can take advantage of the compiler checking to make sure you actually are overriding a method when you think you are. This way, if you make a common mistake of misspelling a method name or not correctly matching the parameters, you will be warned that you method does not actually override as you think it does. Secondly, it makes your code easier to understand because it is more obvious when methods are overwritten.

Additionally, in Java 1.6 you can use it to mark when a method implements an interface for the same benefits. I think it would be better to have a separate annotation (like @Implements), but it's better than nothing.

Dave L.
Along the same lines as "easier to understand", the IDEs will spot the @Override annotation and visually flag the overriding method in the editor.
Bob Cross
Some IDEs will flag an overridden method that is missing the @Override annotation as well.
Jay R.
The other benefit is that if the parent class changes, the compiler will make sure that the child classes have been updated as well.
David
@Jay R.: True. As a matter of fact, e.g. Eclipse can even automatically add the @Override if it is missing.
sleske
In case anyone else got here because of the apparently undocumented change from 1.5 to 1.6 for @Overrides on methods coming from interfaces, http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5008260 seems to be the corresponding bug. (Thanks for pointing it out, Dave L.!)
hheimbuerger
+3  A: 

Using the @Override annotation acts as a compile-time safeguard against a common programming mistake. It will throw a compilation error if you have the annotation on a method you're not actually overriding the superclass method.

The most common case where this is useful is when you are changing a method in the base class to have a different parameter list. A method in a subclass that used to override the superclass method will no longer do so due the changed method signature. This can sometimes cause strange and unexpected behavior, especially when dealing with complex inheritance structures. The @Override annotation safeguards against this.

toluju
+1  A: 

If you find yourself overriding (non-abstract) methods very often, you probably want to take a look at your design. It is very useful when the compiler would not otherwise catch the error. For instance trying to override initValue() in ThreadLocal, which I have done.

Using @Override when implementing interface methods (1.6+ feature) seems a bit overkill for me. If you have loads of methods some of which override and some don't, that probably bad design again (and your editor will probably show which is which if you don't know).

Tom Hawtin - tackline
Actually, it is also nice for overriden interface methods. If I e.g. remove an old, deprecated method from an interface, that method should be removed from all implementing classes as well - easy to spot those if they use @override.
DaDaDom
+2  A: 

The best practive is to always use it (or have the IDE fill them for you)

@Override usefulness is to detect changes in parent classes which has not been reported down the hierarchy. Without it, you can change a method signature and forget to alter its overrides, with @Override, the compiler will catch it for you.

That kind of safety net is always good to have.

+26  A: 

I think it is most useful as a compile-time reminder that the intention of the method is to override a parent method. As an example:

protected boolean displaySensitiveInformation() {
  return false;
}

You will often see something like the above method that overrides a method in the base class. This is an important implementation detail of this class -- we don't want sensitive information to be displayed.

Suppose this method is changed in the parent class to

protected boolean displaySensitiveInformation(Context context) {
  return true;
}

This change will not cause any compile time errors or warnings - but it completely changes the intended behavior of the subclass.

To answer your question: you should use the @Override annotation if the lack of a method with the same signature in a superclass is indicative of a bug.

jon
excellent. I just got burned by note doing this today :)
Yar
+1 for "indicative of a bug".
Thorbjørn Ravn Andersen
+2  A: 

@Override on interfaces actually are helpful, because you will get warnings if you change the interface.

Asgeir S. Nilsen
+2  A: 

I use it everywhere. On the topic of the effort for marking methods, I let Eclipse do it for me so, it's no additional effort.

I'm religious about continuous refactoring.... so, I'll use every little thing to make it go more smoothly.

willCode4Beer
+2  A: 

Its best to use it for every method intended as an override, and Java 6+, every method intended as an implementation of an interface.

First, it catches mispellings like "hashcode" instead of "hashCode" at compile-time. It can be baffling to debug why the result of your method doesn't seem to match your code when the real cause is that your code is never invoked.

Also, if a superclass changes a method signature, overrides of the older signature can be "orphaned", left behind as confusing dead code. The @Override annotation will help you identify these orphans so that they can be modified to match the new signature.

erickson
+10  A: 

There are many good answers here, so let me offer another way to look at it...

There is no overkill when you are coding. It doesn't cost you anything to type @override, but the savings can be immense if you misspelled a method name or got the signature slightly wrong.

Think about it this way: In the time you navigated here and typed this post, you pretty much used more time than you will spend typing @override for the rest of your life; but one error it prevents can save you hours.

Java does all it can to make sure you didn't make any mistakes at edit/compile time, this is a virtually free way to solve an entire class of mistakes that aren't preventable in any other way outside of comprehensive testing.

Could you come up with a better mechanism in Java to ensure that when the user intended to override a method, he actually did?

Another neat effect is that if you don't provide the annotation it will warn you at compile time that you accidentally overrode a parent method--something that could be significant if you didn't intend to do it.

Bill K
"There is no overkill when you are coding." I agree with this, which is why I find dynamic langs so wrong (though 100% of my paid work is in ruby right now).
Yar
+1: I have had, maybe, 10 bugs caused by a mistake in overriding - the time required to find any one of them would easily have exceeded the time to type @Override on every one of my overriding methods. Besides, if @Override is some burdensome, you are probably over-using inheritance.
Software Monkey
One very real downside is that you make the code harder to read by littering it with snails. Perhaps this is a fault of my IDE, but I have experienced this myself.
phyzome
@phyzome it can't be anywhere near as horrific as implementing a generic class--sometimes even using a generic class seems to make the code virtually unreadable. Since (as you say) annotations aren't generally interesting to programmers, perhaps eclipse can be told to hide them?
Bill K
@phyzome If you find the "Snails" cumbersome, you aren't using ANYWHERE NEAR enough comments. They should just be a single line above your method header which should be about as big as your method in most cases (a few lines) to provide decent hover text and javadocs. I guess I'm saying that the problem is not the Snails, it's your reading habits. Are all those parentheses in the code bothering you as well?
Bill K
+2  A: 

Another thing it does is it makes it more obvious when reading the code that it is changing the behavior of the parent class. Than can help in debugging.

Also, in Joshua Block's book Effective Java (2nd edition), item 36 gives more details on the benefits of the annotation.

Diastrophism
A: 

@Override on interface implementation is inconsistent since there is no such thing as "overriding an interface" in java.

@Override on interface implementation is useless since in practise it catches no bugs that the compilation wouldn't catch anyway. There is only one, far fetched scenario where override on implementers actually does something: If you implement an interface, and the interface REMOVES methods, you will be notified on compile time that you should remove the unused implementations. Notice that if the new version of the interface has NEW or CHANGED methods you'll obviously get a compile error anyways as you're not implementing the new stuff.

@Override on interface implementers should never have been permitted in 1.6, and with eclipse sadly choosing to auto-insert the annotations as default behavior, we get a lot of cluttered source files. When reading 1.6 code, you cannot see from the @Override annotation if a method actually overrides a method in the superclass or just implements an interface.

Using @Override when actually overriding a method in a superclass is fine.

Rune
There are varying opinions on that point. See http://stackoverflow.com/questions/212614/should-a-method-that-implements-an-interface-method-be-annotated-with-override .
sleske
+2  A: 

To take advantage from compiler checking you should always use Override annotation. But don’t forget that Java Compiler 1.5 will not allow this annotation when overriding interface methods. You just can use it to override class methods (abstract, or not).

Some IDEs, as Eclipse, even configured with Java 1.6 runtime or higher, they maintain compliance with Java 1.5 and don’t allow the use @override as described above. To avoid that behaviour you must go to: Project Properties ->Java Compiler -> Check “Enable Project Specific Settings” -> Choose “Compiler Compliance Level” = 6.0, or higher.

I like to use this annotation every time I am overriding a method independently, if the base is an interface, or class.

This helps you avoiding some typical errors, as when you are thinking that you are overriding an event handler and then you see nothing happening. Imagine you want to add an event listener to some UI component:

someUIComponent.addMouseListener(new MouseAdapter(){
  public void mouseEntered() {
     ...do something...
  }
});

The above code compiles and run, but if you move the mouse inside someUIComponent the “do something” code will note run, because actually you are not overriding the base method mouseEntered(MouseEvent ev). You just create a new parameter-less method mouseEntered(). Instead of that code, if you have used the @Override annotation you have seen a compile error and you have not been wasting time thinking why your event handler was not running.

+1  A: 
  • Used only on method declarations.
  • Indicates that the annotated method declaration overrides a declaration in supertype.

If used consistently, it protects you from a large class of nefarious bugs.

Use @Override annotation to avoid these bugs: (Spot the bug in the following code:)

public class Bigram {
    private final char first;
    private final char second;
    public Bigram(char first, char second) {
        this.first  = first;
        this.second = second;
    }
    public boolean equals(Bigram b) {
        return b.first == first && b.second == second;
    }
    public int hashCode() {
        return 31 * first + second;
    }

    public static void main(String[] args) {
        Set<Bigram> s = new HashSet<Bigram>();
        for (int i = 0; i < 10; i++)
            for (char ch = 'a'; ch <= 'z'; ch++)
                s.add(new Bigram(ch, ch));
        System.out.println(s.size());
    }
}

source: Effective Java

HanuAthena
Eduardo León
Did you know that your link shows a 'you must subscribe' message covering the useful part of that page?
Adriano Varoli Piazza
@Adriano: Sorry dude!! Am helpless!! When I wrote the 'answer', it was available. No worries..buy the book. It's worth to have it!!
HanuAthena
The equals method does not override:The original `Object::equals` is `boolean equals(Object)`, while the overridden `equals` is `boolean equals(Bigram)`, which has a different method signature, which does not override. Adding @Override to the `equals` will detect this blunder.
SHiNKiROU
+1  A: 

It seems that the wisdom here is changing. Today I installed IntelliJ IDEA 9 and noticed that its "missing @Override inspection" now catches not just implemented abstract methods, but implemented interface methods as well. In my employer's code base and in my own projects, I've long had the habit to only use @Override for the former -- implemented abstract methods. However, rethinking the habit, the merit of using the annotations in both cases becomes clear. Despite being more verbose, it does protect against the fragile base class problem (not as grave as C++-related examples) where the interface method name changes, orphaning the would-be implementing method in a derived class.

Of course, this scenario is mostly hyperbole; the derived class would no longer compile, now lacking an implementation of the renamed interface method, and today one would likely use a Rename Method refactoring operation to address the entire code base en masse.

Given that IDEA's inspection is not configurable to ignore implemented interface methods, today I'll change both my habit and my team's code review criteria.

seh
A: 

Simple , when you wanna override a method present in your super class , use @Override annotation to make a correct override , the compiler will warn you if you dont override it correctly

Sree
A: 

It makes absolutely no sense to use @Override when implementing an interface method. There's no advantage to using it in that case--the compiler will already catch your mistake, so it's just unnecessary clutter.

Steve R.
Using `@Override` on an interface will force you to notice when a method in the interface is removed.
Alex B
@Alex: Removing methods in an interface is a breaking change, like adding them. Once an interface is published, it's effectively locked in unless you have complete control over all the code using it.
Software Monkey
@Software Monkey: That's quite common in large codebases.
phyzome
A: 

Be careful when you use Override, because you can't use reverse engineer in starUML. Make the uml first.

HJ-INCPP
A: 

If your IDE is good enough, you can forget the @Override and live happily ever after !

DucQuoc.wordpress.com
A: 

Hi Frnz, Override annotation is used to take advantage of the compiler, for checking whether you actually are overriding a method from parent class. It is used to notify if you make any mistake like mistake of misspelling a method name, mistake of not correctly matching the parameters

Siva